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,
1141 'paynum_ref' => \$paynum,
1144 return { 'error' => $error } if $error;
1146 #no error, so order the fee package if applicable...
1147 my $conf = new FS::Conf;
1148 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1149 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1151 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1153 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1155 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1156 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1159 #and generate an invoice for it now too
1160 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1161 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1166 $cust_main->apply_payments;
1168 if ( $validate->{'save'} ) {
1169 my $new = new FS::cust_main { $cust_main->hash };
1170 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1171 $new->set( $_ => $validate->{$_} )
1172 foreach qw( payname paystart_month paystart_year payissue payip );
1173 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1175 my $bill_location = FS::cust_location->new({
1176 map { $_ => $validate->{$_} }
1177 qw(address1 address2 city state country zip)
1179 $new->set('bill_location' => $bill_location);
1180 # but don't allow the service address to change this way.
1182 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1183 $new->set( $_ => $validate->{$_} )
1184 foreach qw( payname payip paytype paystate
1185 stateid stateid_state );
1186 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1188 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1189 $new->set( 'paydate' => $validate->{'paydate'} );
1190 my $error = $new->replace($cust_main);
1192 #no, this causes customers to process their payments again
1193 #return { 'error' => $error };
1194 #XXX just warn verosely for now so i can figure out how these happen in
1195 # the first place, eventually should redirect them to the "change
1196 #address" page but indicate the payment did process??
1197 delete($validate->{'payinfo'}); #don't want to log this!
1198 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1199 "NEW: ". Dumper($new)."\n".
1200 "OLD: ". Dumper($cust_main)."\n".
1201 "PACKET: ". Dumper($validate)."\n";
1209 my $receipt_html = '';
1211 # currently supported for realtime CC only; send receipt data to SS
1212 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1215 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1218 <TD ALIGN="right">Payment#</TD>
1219 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1223 <TD ALIGN="right">Date</TD>
1225 <TD BGCOLOR="#FFFFFF"><B>! .
1226 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1232 <TD ALIGN="right">Amount</TD>
1233 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1238 <TD ALIGN="right">Payment method</TD>
1239 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1252 'amount' => sprintf('%.2f', $cust_pay->paid),
1253 'date' => $cust_pay->_date,
1254 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1255 'time_pretty' => time2str('%T', $cust_pay->_date),
1256 'auth_num' => $cust_pay->auth,
1257 'order_num' => $cust_pay->order_number,
1258 'receipt_html' => $receipt_html,
1265 'receipt_html' => '',
1272 sub realtime_collect {
1275 my $session = _cache->get($p->{'session_id'})
1276 or return { 'error' => "Can't resume session" }; #better error message
1278 my $custnum = $session->{'custnum'};
1280 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1281 or return { 'error' => "unknown custnum $custnum" };
1284 if ( $p->{'amount'} ) {
1285 $amount = $p->{'amount'};
1287 elsif ( $session->{'pkgnum'} ) {
1288 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1291 $amount = $cust_main->balance;
1294 my $error = $cust_main->realtime_collect(
1295 'method' => $p->{'method'},
1296 'amount' => $amount,
1297 'pkgnum' => $session->{'pkgnum'},
1298 'session_id' => $p->{'session_id'},
1302 return { 'error' => $error } unless ref( $error );
1304 return { 'error' => '', amount => $amount, %$error };
1307 sub start_thirdparty {
1309 my $session = _cache->get($p->{'session_id'})
1310 or return { 'error' => "Can't resume session" }; #better error message
1311 my $custnum = $session->{'custnum'};
1312 my $cust_main = FS::cust_main->by_key($custnum);
1314 my $amount = $p->{'amount'}
1315 or return { error => 'no amount' };
1317 my $result = $cust_main->create_payment(
1318 'method' => $p->{'method'},
1319 'amount' => $p->{'amount'},
1320 'pkgnum' => $session->{'pkgnum'},
1321 'session_id' => $p->{'session_id'},
1324 if ( ref($result) ) { # hashref or error
1327 return { error => $result };
1331 sub finish_thirdparty {
1333 my $session_id = delete $p->{'session_id'};
1334 my $session = _cache->get($session_id)
1335 or return { 'error' => "Can't resume session" };
1336 my $custnum = $session->{'custnum'};
1337 my $cust_main = FS::cust_main->by_key($custnum);
1339 if ( $p->{_cancel} ) {
1340 # customer backed out of making a payment
1341 return $cust_main->cancel_payment( $session_id );
1343 my $result = $cust_main->execute_payment( $session_id, %$p );
1344 if ( ref($result) ) {
1347 return { error => $result };
1351 sub process_payment_order_pkg {
1354 my $hr = process_payment($p);
1355 return $hr if $hr->{'error'};
1360 sub process_payment_order_renew {
1363 my $hr = process_payment($p);
1364 return $hr if $hr->{'error'};
1369 sub process_prepay {
1373 my $session = _cache->get($p->{'session_id'})
1374 or return { 'error' => "Can't resume session" }; #better error message
1378 my $custnum = $session->{'custnum'};
1380 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1381 or return { 'error' => "unknown custnum $custnum" };
1383 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1384 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1392 return { 'error' => $error } if $error;
1394 return { 'error' => '',
1395 'amount' => $amount,
1396 'seconds' => $seconds,
1397 'duration' => duration_exact($seconds),
1398 'upbytes' => $upbytes,
1399 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1400 'downbytes' => $downbytes,
1401 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1402 'totalbytes'=> $totalbytes,
1403 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1410 my $session = _cache->get($p->{'session_id'})
1411 or return { 'error' => "Can't resume session" }; #better error message
1413 my $custnum = $session->{'custnum'};
1415 my $invnum = $p->{'invnum'};
1417 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1418 'custnum' => $custnum } )
1419 or return { 'error' => "Can't find invnum" };
1423 return { 'error' => '',
1424 'invnum' => $invnum,
1425 'invoice_text' => join('', $cust_bill->print_text ),
1426 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1433 my $session = _cache->get($p->{'session_id'})
1434 or return { 'error' => "Can't resume session" }; #better error message
1436 my $custnum = $session->{'custnum'};
1438 my $invnum = $p->{'invnum'};
1440 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1441 'custnum' => $custnum } )
1442 or return { 'error' => "Can't find invnum" };
1446 return { 'error' => '',
1447 'invnum' => $invnum,
1448 'invoice_pdf' => $cust_bill->print_pdf({
1449 'unsquelch_cdr' => 1,
1450 'locale' => $p->{'locale'},
1456 sub legacy_invoice {
1458 my $session = _cache->get($p->{'session_id'})
1459 or return { 'error' => "Can't resume session" }; #better error message
1461 my $custnum = $session->{'custnum'};
1463 my $legacyinvnum = $p->{'legacyinvnum'};
1466 'legacyinvnum' => $legacyinvnum,
1467 'custnum' => $custnum,
1470 my $legacy_cust_bill =
1471 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1472 || qsearchs('legacy_cust_bill', \%hash )
1473 or return { 'error' => "Can't find legacyinvnum" };
1477 return { 'error' => '',
1478 'legacyinvnum' => $legacyinvnum,
1479 'legacyid' => $legacy_cust_bill->legacyid,
1480 'invoice_html' => $legacy_cust_bill->content_html,
1485 sub legacy_invoice_pdf {
1487 my $session = _cache->get($p->{'session_id'})
1488 or return { 'error' => "Can't resume session" }; #better error message
1490 my $custnum = $session->{'custnum'};
1492 my $legacyinvnum = $p->{'legacyinvnum'};
1494 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1495 'legacyinvnum' => $legacyinvnum,
1496 'custnum' => $custnum,
1497 }) or return { 'error' => "Can't find legacyinvnum" };
1501 return { 'error' => '',
1502 'legacyinvnum' => $legacyinvnum,
1503 'legacyid' => $legacy_cust_bill->legacyid,
1504 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1512 #sessioning for this? how do we get the session id to the backend invoice
1513 # template so it can add it to the link, blah
1516 if ( $p->{'invnum'} ) {
1517 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1518 or return { 'error' => 'unknown invnum' };
1519 $agentnum = $cust_bill->cust_main->agentnum;
1522 my $templatename = $p->{'template'} || $p->{'templatename'};
1524 #false laziness-ish w/view/cust_bill-logo.cgi
1526 my $conf = new FS::Conf;
1527 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1528 $templatename = "_$1";
1533 my $filename = "logo$templatename.png";
1535 return { 'error' => '',
1536 'logo' => $conf->config_binary($filename, $agentnum),
1537 'content_type' => 'image/png', #should allow gif, jpg too
1544 my $session = _cache->get($p->{'session_id'})
1545 or return { 'error' => "Can't resume session" }; #better error message
1547 my $custnum = $session->{'custnum'};
1549 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1550 or return { 'error' => "unknown custnum $custnum" };
1552 my $conf = new FS::Conf;
1554 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1556 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1560 return { 'error' => '',
1561 'balance' => $cust_main->balance,
1564 my $owed = $_->owed;
1566 +{ 'invnum' => $_->invnum,
1567 '_date' => $_->_date,
1568 'date' => time2str("%b %o, %Y", $_->_date),
1569 'date_short' => time2str("%m-%d-%Y", $_->_date),
1570 'previous' => sprintf('%.2f', ($_->previous)[0]),
1571 'charged' => sprintf('%.2f', $_->charged),
1572 'owed' => sprintf('%.2f', $owed),
1573 'balance' => sprintf('%.2f', $balance),
1578 'legacy_invoices' => [
1580 +{ 'legacyinvnum' => $_->legacyinvnum,
1581 'legacyid' => $_->legacyid,
1582 '_date' => $_->_date,
1583 'date' => time2str("%b %o, %Y", $_->_date),
1584 'date_short' => time2str("%m-%d-%Y", $_->_date),
1585 'charged' => sprintf('%.2f', $_->charged),
1586 'has_content' => ( length($_->content_pdf)
1587 || length($_->content_html) ),
1597 my $session = _cache->get($p->{'session_id'})
1598 or return { 'error' => "Can't resume session" }; #better error message
1600 my $custnum = $session->{'custnum'};
1602 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1603 or return { 'error' => "unknown custnum $custnum" };
1605 my @errors = $cust_main->cancel( 'quiet'=>1 );
1607 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1609 return { 'error' => $error };
1616 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1617 return { 'error' => $session } if $context eq 'error';
1619 my $search = { 'custnum' => $custnum };
1620 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1621 my $cust_main = qsearchs('cust_main', $search )
1622 or return { 'error' => "unknown custnum $custnum" };
1624 my $conf = new FS::Conf;
1625 my $immutable = $conf->exists('selfservice_immutable-package');
1627 # the duplication below is necessary:
1628 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1629 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1630 # non-backwards-compatible change breaking the software of anyone using the API
1631 # instead of the stock selfservice
1632 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1633 if( $conf->exists('selfservice_server-view-wholesale') ) {
1634 return { 'svcnum' => $session->{'svcnum'},
1635 'custnum' => $custnum,
1636 'cust_pkg' => [ map {
1638 immutable => $immutable,
1639 part_pkg => [ map $_->hashref, $_->part_pkg ],
1641 [ map $_->hashref, $_->available_part_svc ],
1643 [ map { my $ref = { $_->hash,
1644 label => [ $_->label ],
1646 $ref->{_password} = $_->svc_x->_password
1647 if $context eq 'agent'
1648 && $conf->exists('agent-showpasswords')
1649 && $_->part_svc->svcdb eq 'svc_acct';
1654 } $cust_main->cust_pkg
1657 small_custview( $cust_main, $conf->config('countrydefault') ),
1658 'wholesale_view' => 1,
1659 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1660 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1661 'lnp' => $conf->exists('svc_phone-lnp'),
1665 { 'svcnum' => $session->{'svcnum'},
1666 'custnum' => $custnum,
1667 'cust_pkg' => [ map {
1668 my $primary_cust_svc = $_->primary_cust_svc;
1671 immutable => $immutable,
1672 pkg_label => $_->pkg_locale,
1673 status => $_->status,
1674 statuscolor => $_->statuscolor,
1676 [ map { $_->hashref }
1677 grep { $_->selfservice_access ne 'hidden' }
1678 $_->available_part_svc
1681 [ map { my $ref = { $_->hash,
1682 label => [ $_->label ],
1684 $ref->{_password} = $_->svc_x->_password
1685 if $context eq 'agent'
1686 && $conf->exists('agent-showpasswords')
1687 && $_->part_svc->svcdb eq 'svc_acct';
1688 $ref->{svchash} = { $_->svc_x->hash } if
1689 $_->part_svc->svcdb eq 'svc_phone';
1690 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1691 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1694 grep { $_->part_svc->selfservice_access ne 'hidden' }
1699 ? { $primary_cust_svc->hash,
1700 label => [ $primary_cust_svc->label ],
1701 finger => $primary_cust_svc->svc_x->finger, #uuh
1702 $primary_cust_svc->part_svc->hash,
1706 } $cust_main->ncancelled_pkgs
1709 small_custview( $cust_main, $conf->config('countrydefault') ),
1710 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1718 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1719 return { 'error' => $session } if $context eq 'error';
1721 my $conf = new FS::Conf;
1723 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1724 my $search = { 'custnum' => $custnum };
1725 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1726 my $cust_main = qsearchs('cust_main', $search )
1727 or return { 'error' => "unknown custnum $custnum" };
1729 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1730 if ( ! $pkgnum && $p->{'svcnum'} ) {
1731 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1732 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1736 my @cust_pkg_usage = ();
1737 foreach my $cust_pkg ( $p->{'ncancelled'}
1738 ? $cust_main->ncancelled_pkgs
1739 : $cust_main->unsuspended_pkgs ) {
1740 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1741 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1742 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1745 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1748 foreach (@cust_pkg_usage) {
1749 my $part = $_->part_pkg_usage;
1750 my $tag = $part->description . ($part->shared ? 1 : 0);
1751 my $row = $usage_pools{$tag}
1752 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1753 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1754 $row->[2] += $part->minutes; # minutes total
1756 } # otherwise just leave them empty
1758 if ( $p->{'svcdb'} ) {
1759 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1761 : ref($p->{'svcdb'}) eq 'ARRAY'
1762 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1763 : { $p->{'svcdb'} => 1 };
1764 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1767 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1770 my @svcs; # stuff to return to the client
1771 foreach my $cust_svc (@cust_svc) {
1772 my $svc_x = $cust_svc->svc_x;
1773 my($label, $value) = $cust_svc->label;
1774 my $part_svc = $cust_svc->part_svc;
1775 my $svcdb = $part_svc->svcdb;
1776 my $cust_pkg = $cust_svc->cust_pkg;
1777 my $part_pkg = $cust_pkg->part_pkg;
1780 'svcnum' => $cust_svc->svcnum,
1781 'display_svcnum' => $cust_svc->display_svcnum,
1785 'pkg_label' => $cust_pkg->pkg_locale,
1786 'pkg_status' => $cust_pkg->status,
1787 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1790 # would it make sense to put this in a svc_* method?
1792 if ( $svcdb eq 'svc_acct' ) {
1793 foreach (qw(username email finger seconds)) {
1794 $hash{$_} = $svc_x->$_;
1800 'upbytes' => display_bytecount($svc_x->upbytes),
1801 'downbytes' => display_bytecount($svc_x->downbytes),
1802 'totalbytes' => display_bytecount($svc_x->totalbytes),
1804 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1805 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1806 'recharge_upbytes' =>
1807 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1808 'recharge_downbytes' =>
1809 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1810 'recharge_totalbytes' =>
1811 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1816 } elsif ( $svcdb eq 'svc_dsl' ) {
1818 $hash{'phonenum'} = $svc_x->phonenum;
1819 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1820 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1821 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1824 $hash{'name'} = $cust_main->name;
1826 # no usage to hide here
1828 } elsif ( $svcdb eq 'svc_phone' ) {
1830 # could potentially show lots of things...
1831 $hash{'outbound'} = 1;
1832 $hash{'inbound'} = 0;
1833 if ( $part_pkg->plan eq 'voip_inbound' ) {
1834 $hash{'outbound'} = 0;
1835 $hash{'inbound'} = 1;
1836 } elsif ( $part_pkg->option('selfservice_inbound_format')
1837 or $conf->config('selfservice-default_inbound_cdr_format')
1839 $hash{'inbound'} = 1;
1841 foreach (qw(inbound outbound)) {
1842 # hmm...we can't filter by status here, because there might
1843 # not be cdr_terminations at all. have to go by date.
1844 # find all since the last bill date.
1845 # XXX cdr types? we are going to need them.
1847 my $sum_cdr = $svc_x->sum_cdrs(
1848 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1849 'begin' => ($cust_pkg->last_bill || 0),
1851 'disable_charged_party' => 1,
1853 $hash{$_} = $sum_cdr->hashref;
1856 } # not hiding usage
1860 } # foreach $cust_svc
1863 'svcnum' => $session->{'svcnum'},
1864 'custnum' => $custnum,
1865 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1866 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1869 map { $usage_pools{$_} }
1873 'hide_usage' => $hide_usage,
1878 sub _customer_svc_x {
1879 my($custnum, $svcnum, $table) = (shift, shift, shift);
1880 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1882 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1883 my $search = " AND custnum = $1";
1884 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1887 'table' => ($table || 'svc_acct'),
1888 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1889 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1890 #'LEFT JOIN cust_main USING ( custnum ) ',
1891 'hashref' => $hashref,
1892 'extra_sql' => $search, #important
1897 sub svc_status_html {
1900 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1901 return { 'error' => $session } if $context eq 'error';
1903 #XXX only svc_dsl for now
1904 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1905 or return { 'error' => "Service not found" };
1907 my $html = $svc_x->getstatus_html;
1909 return { 'html' => $html };
1913 sub svc_status_hash {
1916 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1917 return { 'error' => $session } if $context eq 'error';
1919 #XXX only svc_acct for now
1920 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1921 or return { 'error' => "Service not found" };
1923 my ( $html, $hashref ) = $svc_x->export_getstatus;
1928 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1929 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1930 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1931 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1932 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1935 my( $p, $method ) = @_;
1937 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1938 return { 'error' => $session } if $context eq 'error';
1940 #XXX only svc_acct for now
1941 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1942 or return { 'error' => "Service not found" };
1944 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1946 my $error = $svc_x->$method($p); #$p? returns error?
1947 return { 'error' => $error } if $error;
1949 return {}; #? { 'error' => '' }
1953 sub acct_forward_info {
1956 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1957 return { 'error' => $session } if $context eq 'error';
1959 my $svc_forward = _customer_svc_x( $custnum,
1960 { 'srcsvc' => $p->{'svcnum'} },
1963 or return { 'error' => '',
1967 return { 'error' => '',
1968 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1973 sub process_acct_forward {
1975 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1976 return { 'error' => $session } if $context eq 'error';
1978 my $old = _customer_svc_x( $custnum,
1979 { 'srcsvc' => $p->{'svcnum'} },
1983 if ( $p->{'dst'} eq '' ) {
1985 my $error = $old->delete;
1986 return { 'error' => $error };
1988 return { 'error' => '' };
1991 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1992 'dst' => $p->{'dst'},
1997 $new->svcnum($old->svcnum);
1998 my $cust_svc = $old->cust_svc;
1999 $new->svcpart($old->svcpart);
2000 $new->pkgnuym($old->pkgnum);
2001 $error = $new->replace($old);
2003 my $conf = new FS::Conf;
2004 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2006 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2007 or return { 'error' => 'No service' }; #how would we even get here?
2009 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2011 $error = $new->insert;
2014 return { 'error' => $error };
2018 sub list_dsl_devices {
2021 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2022 return { 'error' => $session } if $context eq 'error';
2024 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2025 or return { 'error' => "Service not found" };
2028 'devices' => [ map {
2029 +{ 'mac_addr' => $_->mac_addr };
2030 } $svc_dsl->dsl_device
2036 sub add_dsl_device {
2039 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2040 return { 'error' => $session } if $context eq 'error';
2042 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2043 or return { 'error' => "Service not found" };
2045 return { 'error' => 'No MAC address supplied' }
2046 unless length($p->{'mac_addr'});
2048 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2049 'mac_addr' => scalar($p->{'mac_addr'}),
2051 my $error = $dsl_device->insert;
2052 return { 'error' => $error };
2056 sub delete_dsl_device {
2059 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2060 return { 'error' => $session } if $context eq 'error';
2062 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2063 or return { 'error' => "Service not found" };
2065 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2066 'mac_addr' => scalar($p->{'mac_addr'}),
2069 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2071 my $error = $dsl_device->delete;
2072 return { 'error' => $error };
2078 _usage_details( \&_port_graph, $p,
2079 'svcdb' => 'svc_port',
2084 my($svc_port, $begin, $end) = @_;
2086 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2087 push @usage, { 'png' => $pngOrError };
2091 sub _list_svc_usage {
2092 my($svc_acct, $begin, $end) = @_;
2094 foreach my $part_export (
2095 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2096 qw( sqlradius sqlradius_withdomain )
2098 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2103 sub list_svc_usage {
2104 _usage_details(\&_list_svc_usage, @_);
2107 sub _list_support_usage {
2108 my($svc_acct, $begin, $end) = @_;
2110 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2111 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2113 push @usage, { 'seconds' => $_->seconds,
2114 'support' => $_->support,
2115 '_date' => $_->_date,
2116 'id' => $_->transaction_id,
2117 'creator' => $_->creator,
2118 'subject' => $_->subject,
2119 'status' => $_->status,
2120 'ticketid' => $_->ticketid,
2126 sub list_support_usage {
2127 _usage_details(\&_list_support_usage, @_);
2130 sub _list_cdr_usage {
2131 # XXX CDR type support...
2132 # XXX any way to do a paged search on this?
2133 # we have to return the results all at once...
2134 my($svc_phone, $begin, $end, %opt) = @_;
2135 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2136 $svc_phone->get_cdrs(
2139 'disable_charged_party' => 1,
2144 sub list_cdr_usage {
2146 _usage_details( \&_list_cdr_usage, $p,
2147 'svcdb' => 'svc_phone',
2151 sub _usage_details {
2152 my($callback, $p, %opt) = @_;
2153 my $conf = FS::Conf->new;
2155 if ( $conf->exists('selfservice_hide-usage') ) {
2156 return { 'error' => 'Viewing usage is not allowed.' };
2159 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2160 return { 'error' => $session } if $context eq 'error';
2162 my $search = { 'svcnum' => $p->{'svcnum'} };
2163 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2165 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2167 my $svc_x = qsearchs( $svcdb, $search );
2168 return { 'error' => 'No service selected in list_svc_usage' }
2171 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2172 my $freq = $cust_pkg->part_pkg->freq;
2175 if ( $svcdb eq 'svc_phone' ) {
2177 if ( $p->{inbound} ) {
2178 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2179 || $conf->config('selfservice-default_inbound_cdr_format')
2180 || 'source_default';
2181 $callback_opt{inbound} = 1;
2183 $format = $cust_pkg->part_pkg->option('selfservice_format')
2184 || $conf->config('selfservice-default_cdr_format')
2188 $callback_opt{format} = $format;
2189 $callback_opt{use_clid} = 1;
2190 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2193 my $start = $cust_pkg->setup;
2194 #my $end = $cust_pkg->bill; # or time?
2197 unless ( $p->{beginning} ) {
2198 $p->{beginning} = $cust_pkg->last_bill;
2199 $p->{ending} = $end;
2202 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2203 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2205 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2209 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2210 # ugly kludge, I know
2211 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2212 if (defined $delete_col) {
2213 delete($_->[$delete_col]) foreach ($header, @usage);
2217 #kinda false laziness with FS::cust_main::bill, but perhaps
2218 #we should really change this bit to DateTime and DateTime::Duration
2220 #change this bit to use Date::Manip? CAREFUL with timezones (see
2221 # mailing list archive)
2222 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2223 (localtime($p->{ending}) )[0,1,2,3,4,5];
2224 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2225 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2227 if ( $freq =~ /^\d+$/ ) {
2229 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2231 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2232 } elsif ( $freq =~ /^(\d+)w$/ ) {
2234 $nmday += $weeks * 7;
2235 $pmday -= $weeks * 7;
2236 } elsif ( $freq =~ /^(\d+)d$/ ) {
2240 } elsif ( $freq =~ /^(\d+)h$/ ) {
2245 return { 'error' => "unparsable frequency: ". $freq };
2248 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2249 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2253 'svcnum' => $p->{svcnum},
2254 'beginning' => $p->{beginning},
2255 'ending' => $p->{ending},
2256 'inbound' => $p->{inbound},
2257 'previous' => ($previous > $start) ? $previous : $start,
2258 'next' => ($next < $end) ? $next : $end,
2259 'header' => $header,
2267 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2268 return { 'error' => $session } if $context eq 'error';
2270 my $search = { 'custnum' => $custnum };
2271 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2272 my $cust_main = qsearchs('cust_main', $search )
2273 or return { 'error' => "unknown custnum $custnum" };
2275 my $status = $cust_main->status;
2276 #false laziness w/ClientAPI/Signup.pm
2278 my $cust_pkg = new FS::cust_pkg ( {
2279 'custnum' => $custnum,
2280 'pkgpart' => $p->{'pkgpart'},
2282 my $error = $cust_pkg->check;
2283 return { 'error' => $error } if $error;
2286 unless ( $p->{'svcpart'} eq 'none' ) {
2290 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2292 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2293 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2294 $svcdb = $part_svc->svcdb;
2296 $svcdb = 'svc_acct';
2298 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2301 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2302 'svc_domain' => [ qw( domain ) ],
2303 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2304 'svc_external' => [ qw( id title ) ],
2305 'svc_pbx' => [ qw( id title ) ],
2308 my $svc_x = "FS::$svcdb"->new( {
2309 'svcpart' => $svcpart,
2310 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2313 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2316 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2317 my $acct_snarf = new FS::acct_snarf ( {
2318 'machine' => $p->{"snarf_machine$snarfnum"},
2319 'protocol' => $p->{"snarf_protocol$snarfnum"},
2320 'username' => $p->{"snarf_username$snarfnum"},
2321 '_password' => $p->{"snarf_password$snarfnum"},
2324 push @acct_snarf, $acct_snarf;
2326 $svc_x->child_objects( \@acct_snarf );
2329 my $y = $svc_x->setdefault; # arguably should be in new method
2330 return { 'error' => $y } if $y && !ref($y);
2332 $error = $svc_x->check;
2333 return { 'error' => $error } if $error;
2340 tie my %hash, 'Tie::RefHash';
2341 %hash = ( $cust_pkg => \@svc );
2343 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2344 return { 'error' => $error } if $error;
2346 my $conf = new FS::Conf;
2347 if ( $conf->exists('signup_server-realtime') ) {
2349 my $bill_error = _do_bop_realtime( $cust_main, $status );
2352 $cust_pkg->cancel('quiet'=>1);
2355 $cust_pkg->reexport;
2359 $cust_pkg->reexport;
2362 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2364 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2371 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2372 return { 'error' => $session } if $context eq 'error';
2374 my $conf = new FS::Conf;
2375 my $immutable = $conf->exists('selfservice_immutable-package');
2376 return { 'error' => "Package modification disabled" } if $immutable;
2378 my $search = { 'custnum' => $custnum };
2379 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2380 my $cust_main = qsearchs('cust_main', $search )
2381 or return { 'error' => "unknown custnum $custnum" };
2383 my $status = $cust_main->status;
2384 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2385 or return { 'error' => "unknown package $p->{pkgnum}" };
2387 #if someone does need self-service package change of suspended packages,
2388 # figure out how to be more discriminating
2389 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2390 if $cust_pkg->status eq 'suspended';
2393 my $error = FS::cust_pkg::order( $custnum,
2399 if ( $conf->exists('signup_server-realtime') ) {
2401 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2404 $newpkg[0]->suspend;
2407 $newpkg[0]->reexport;
2411 $newpkg[0]->reexport;
2414 return { error => '', pkgnum => $cust_pkg->pkgnum };
2418 sub order_recharge {
2421 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2422 return { 'error' => $session } if $context eq 'error';
2424 my $search = { 'custnum' => $custnum };
2425 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2426 my $cust_main = qsearchs('cust_main', $search )
2427 or return { 'error' => "unknown custnum $custnum" };
2429 my $status = $cust_main->status;
2430 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2431 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2433 my $svc_x = $cust_svc->svc_x;
2434 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2437 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2438 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2439 recharge_totalbytes );
2440 my $amount = $part_pkg->option('recharge_amount', 1);
2442 my ($l, $v, $d) = $cust_svc->label; # blah
2443 my $pkg = "Recharge $v";
2445 my $bill_error = $cust_main->charge($amount, $pkg,
2446 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2447 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2448 $part_pkg->taxclass); #meh
2450 my $conf = new FS::Conf;
2451 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2453 $bill_error = _do_bop_realtime( $cust_main, $status );
2458 my $error = $svc_x->recharge (\%vhash);
2459 return { 'error' => $error } if $error;
2463 my $error = $bill_error;
2464 $error ||= $svc_x->recharge (\%vhash);
2465 return { 'error' => $error } if $error;
2468 return { error => '', svc => $cust_svc->part_svc->svc };
2472 sub _do_bop_realtime {
2473 my ($cust_main, $status, %opt) = @_;
2475 my $old_balance = $cust_main->balance;
2477 my $bill_error = $cust_main->bill
2478 || $cust_main->apply_payments_and_credits;
2480 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2481 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2483 if ( $cust_main->balance > $old_balance
2484 && $cust_main->balance > 0
2485 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2486 || $status eq 'suspended'
2490 unless ( $opt{'no_credit'} ) {
2491 #this makes sense. credit is "un-doing" the invoice
2492 my $conf = new FS::Conf;
2493 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2494 'self-service decline',
2495 reason_type=>$conf->config('signup_credit_type'),
2497 $cust_main->apply_credits( 'order' => 'newest' );
2500 return { 'error' => '_decline', 'bill_error' => $bill_error };
2509 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2510 return { 'error' => $session } if $context eq 'error';
2512 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2513 or return { 'error' => "unknown custnum $custnum" };
2515 my @cust_pkg = sort { $a->bill <=> $b->bill }
2516 grep { $_->part_pkg->freq ne '0' }
2517 $cust_main->ncancelled_pkgs;
2519 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2521 my $total = $cust_main->balance;
2524 my $bill = $_->bill;
2525 $total += $_->part_pkg->base_recur($_, \$bill);
2526 my $renew_date = $_->part_pkg->add_freq($_->bill);
2528 'pkgnum' => $_->pkgnum,
2529 'amount' => sprintf('%.2f', $total),
2530 'bill_date' => $_->bill,
2531 'bill_date_pretty' => time2str('%x', $_->bill),
2532 'renew_date' => $renew_date,
2533 'renew_date_pretty' => time2str('%x', $renew_date),
2534 'expire_date' => $_->expire,
2535 'expire_date_pretty' => time2str('%x', $_->expire),
2540 return { 'dates' => \@array };
2544 sub payment_info_renew_info {
2546 my $renew_info = renew_info($p);
2547 my $payment_info = payment_info($p);
2548 return { %$renew_info,
2556 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2557 return { 'error' => $session } if $context eq 'error';
2559 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2560 or return { 'error' => "unknown custnum $custnum" };
2562 my $date = $p->{'date'};
2566 #freeside-daily -n -d $date fs_daily $custnum
2567 $cust_main->bill_and_collect( 'time' => $date,
2568 'invoice_time' => $now,
2569 'actual_time' => $now,
2570 'check_freq' => '1d',
2573 return { 'error' => '' };
2579 my $session = _cache->get($p->{'session_id'})
2580 or return { 'error' => "Can't resume session" }; #better error message
2582 my $custnum = $session->{'custnum'};
2584 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2585 or return { 'error' => "unknown custnum $custnum" };
2587 my $conf = new FS::Conf;
2589 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2590 or return { 'error' => 'Permission denied' };
2592 my $pkgnum = $p->{'pkgnum'};
2594 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2595 'pkgnum' => $pkgnum, } )
2596 or return { 'error' => "unknown pkgnum $pkgnum" };
2598 my $error = $cust_pkg->suspend(reason => $reasonnum);
2599 return { 'error' => $error };
2605 my $session = _cache->get($p->{'session_id'})
2606 or return { 'error' => "Can't resume session" }; #better error message
2608 my $custnum = $session->{'custnum'};
2610 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2611 or return { 'error' => "unknown custnum $custnum" };
2613 my $pkgnum = $p->{'pkgnum'};
2615 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2616 'pkgnum' => $pkgnum, } )
2617 or return { 'error' => "unknown pkgnum $pkgnum" };
2619 my $error = $cust_pkg->cancel('quiet' => 1);
2620 return { 'error' => $error };
2624 sub provision_phone {
2627 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2629 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2630 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2631 return { 'error' => $session } if $context eq 'error';
2633 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2634 return { 'error' => 'service not found' } unless $svc_phone;
2635 return { 'error' => 'invalid svcnum' }
2636 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2638 $svc_phone->email($p->{'email'})
2639 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2640 $svc_phone->forwarddst($p->{'forwarddst'})
2641 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2642 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2643 return { 'error' => $svc_phone->replace };
2647 unless($p->{'lnp'}) {
2648 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2649 $p->{'lnp_status'} = "portingin";
2650 return _provision( 'FS::svc_phone',
2651 [qw(lnp_desired_due_date lnp_other_provider
2652 lnp_other_provider_account phonenum countrycode lnp_status)],
2653 [qw(phonenum countrycode)],
2660 unless (scalar(@bulkdid)) {
2661 return _provision( 'FS::svc_phone',
2662 [qw(phonenum countrycode)],
2663 [qw(phonenum countrycode)],
2669 # bulk DID order case
2671 foreach my $did ( @bulkdid ) {
2672 $did =~ s/[^0-9]//g;
2673 $error = _provision( 'FS::svc_phone',
2674 [qw(phonenum countrycode)],
2675 [qw(phonenum countrycode)],
2677 'pkgnum' => $p->{'pkgnum'},
2678 'svcpart' => $p->{'svcpart'},
2680 'countrycode' => $p->{'countrycode'},
2681 'session_id' => $p->{'session_id'},
2684 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2686 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2689 sub provision_acct {
2691 warn "provision_acct called\n"
2694 return { 'error' => gettext('passwords_dont_match') }
2695 if $p->{'_password'} ne $p->{'_password2'};
2696 return { 'error' => gettext('empty_password') }
2697 unless length($p->{'_password'});
2699 if ($p->{'domsvc'}) {
2700 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2701 qw ( svcpart pkgnum ) );
2702 return { 'error' => gettext('invalid_domain') }
2703 unless ($domains{$p->{'domsvc'}});
2706 warn "provision_acct calling _provision\n"
2708 _provision( 'FS::svc_acct',
2709 [qw(username _password domsvc)],
2710 [qw(username _password domsvc)],
2716 sub provision_external {
2718 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2719 _provision( 'FS::svc_external',
2728 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2729 warn "_provision called for $class\n"
2732 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2733 return { 'error' => $session } if $context eq 'error';
2735 my $search = { 'custnum' => $custnum };
2736 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2737 my $cust_main = qsearchs('cust_main', $search )
2738 or return { 'error' => "unknown custnum $custnum" };
2740 my $pkgnum = $p->{'pkgnum'};
2742 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2744 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2745 'pkgnum' => $pkgnum,
2747 or return { 'error' => "unknown pkgnum $pkgnum" };
2749 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2751 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2752 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2754 warn "creating $class record\n"
2756 my $svc_x = $class->new( {
2757 'pkgnum' => $p->{'pkgnum'},
2758 'svcpart' => $p->{'svcpart'},
2759 map { $_ => $p->{$_} } @$fields
2761 warn "inserting $class record\n"
2763 my $error = $svc_x->insert;
2766 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2768 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2771 my $return = { 'svc' => $part_svc->svc,
2773 map { $_ => $svc_x->get($_) } @$return_fields
2775 warn "_provision returning ". Dumper($return). "\n"
2784 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2785 return { 'error' => $session } if $context eq 'error';
2787 my $search = { 'custnum' => $custnum };
2788 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2789 my $cust_main = qsearchs('cust_main', $search )
2790 or return { 'error' => "unknown custnum $custnum" };
2792 my $pkgnum = $p->{'pkgnum'};
2794 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2795 'pkgnum' => $pkgnum,
2797 or return { 'error' => "unknown pkgnum $pkgnum" };
2799 my $svcpart = $p->{'svcpart'};
2801 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2802 'svcpart' => $svcpart, } )
2803 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2804 my $part_svc = $pkg_svc->part_svc;
2806 my $conf = new FS::Conf;
2809 'svc' => $part_svc->svc,
2810 'svcdb' => $part_svc->svcdb,
2811 'pkgnum' => $pkgnum,
2812 'svcpart' => $svcpart,
2813 'custnum' => $custnum,
2815 'security_phrase' => 0, #XXX !
2816 'svc_acct_pop' => [], #XXX !
2818 'init_popstate' => '',
2823 small_custview( $cust_main, $conf->config('countrydefault') ),
2827 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2828 && $ret->{'svcdb'} eq 'svc_phone') {
2829 $ret->{'svcnum'} = $p->{'svcnum'};
2830 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2831 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2832 $ret->{'email'} = $svc_phone->email;
2833 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2840 sub unprovision_svc {
2843 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2844 return { 'error' => $session } if $context eq 'error';
2846 my $search = { 'custnum' => $custnum };
2847 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2848 my $cust_main = qsearchs('cust_main', $search )
2849 or return { 'error' => "unknown custnum $custnum" };
2851 my $svcnum = $p->{'svcnum'};
2853 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2854 or return { 'error' => "unknown svcnum $svcnum" };
2856 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2857 unless $cust_svc->cust_pkg->custnum == $custnum;
2859 my $conf = new FS::Conf;
2861 return { 'svc' => $cust_svc->part_svc->svc,
2862 'error' => $cust_svc->cancel,
2864 small_custview( $cust_main, $conf->config('countrydefault') ),
2869 sub myaccount_passwd {
2871 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2872 return { 'error' => $session } if $context eq 'error';
2874 return { 'error' => "New passwords don't match." }
2875 if $p->{'new_password'} ne $p->{'new_password2'};
2877 return { 'error' => 'Enter new password' }
2878 unless length($p->{'new_password'});
2880 #my $search = { 'custnum' => $custnum };
2881 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2882 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2883 my $search = " AND custnum = $1";
2884 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2886 my $svc_acct = qsearchs( {
2887 'table' => 'svc_acct',
2888 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2889 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2890 'LEFT JOIN cust_main USING ( custnum ) ',
2891 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2892 'extra_sql' => $search, #important
2894 or return { 'error' => "Service not found" };
2898 my $conf = new FS::Conf;
2900 return { 'error' => 'Incorrect current password.' }
2901 if ( exists($p->{'old_password'})
2902 || $conf->exists('selfservice-password_change_oldpass')
2904 && ! $svc_acct->check_password($p->{'old_password'});
2906 $error = 'Password too short.'
2907 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2908 $error = 'Password too long.'
2909 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2911 $svc_acct->set_password($p->{'new_password'});
2912 $error ||= $svc_acct->replace();
2914 #regular pw change in self-service should change contact pw too, otherwise its
2915 #way too confusing. hell its confusing they're separate at all, but alas.
2916 #need to support the "ISP provides email that's used as a contact email" case
2918 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2919 if ( $contact && $contact->custnum == $custnum ) {
2920 #svc_acct was successful but this one returns an error? "shouldn't happen"
2921 $error ||= $contact->change_password($p->{'new_password'});
2924 my($label, $value) = $svc_acct->cust_svc->label;
2926 return { 'error' => $error,
2933 # sub contact_passwd {
2935 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2936 # return { 'error' => $session } if $context eq 'error';
2938 # return { 'error' => 'Not logged in as a contact.' }
2939 # unless $session->{'contactnum'};
2941 # return { 'error' => "New passwords don't match." }
2942 # if $p->{'new_password'} ne $p->{'new_password2'};
2944 # return { 'error' => 'Enter new password' }
2945 # unless length($p->{'new_password'});
2947 # #my $search = { 'custnum' => $custnum };
2948 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2949 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2950 # my $search = " AND selfservice_access IS NOT NULL ".
2951 # " AND selfservice_access = 'Y' ".
2952 # " AND ( disabled IS NULL OR disabled = '' )".
2953 # " AND custnum IS NOT NULL AND custnum = $1";
2954 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2956 # my $contact = qsearchs( {
2957 # 'table' => 'contact',
2958 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2959 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2960 # 'extra_sql' => $search, #important
2962 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2963 # # deleted since then?
2967 # # use these svc_acct length restrictions??
2968 # my $conf = new FS::Conf;
2969 # $error = 'Password too short.'
2970 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2971 # $error = 'Password too long.'
2972 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2974 # $error ||= $contact->change_password($p->{'new_password'});
2976 # return { 'error' => $error, };
2983 my $info = skin_info($p);
2985 my $conf = new FS::Conf;
2986 my $verification = $conf->config('selfservice-password_reset_verification')
2987 or return { %$info, 'error' => 'Password resets disabled' };
2992 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2994 $contact = FS::contact->by_selfservice_email($p->{'email'});
2996 $cust_main = $contact->cust_main if $contact;
2998 #also look for an svc_acct, otherwise it would be super confusing
3000 my($username, $domain) = split('@', $p->{'email'});
3001 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3002 if ( $svc_domain ) {
3003 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3004 'domsvc' => $svc_domain->svcnum }
3007 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3008 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3010 #precaution: don't change svc_acct password not part of the same
3011 # customer as contact
3012 $svc_acct = '' if ! $cust_pkg
3013 || $cust_pkg->custnum != $cust_main->custnum;
3018 return { %$info, 'error' => 'Email address not found' }
3019 unless $contact || $svc_acct;
3021 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3023 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3024 or return { %$info, 'error' => 'Account not found' };
3026 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3027 'domsvc' => $svc_domain->svcnum }
3029 or return { %$info, 'error' => 'Account not found' };
3031 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3032 or return { %$info, 'error' => 'Account not found' };
3034 $cust_main = $cust_pkg->cust_main;
3039 'email' => sub { 1; },
3041 my( $p, $cust_main ) = @_;
3042 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3043 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3046 my( $p, $cust_main ) = @_;
3047 my $cust_pay = qsearchs({
3048 'table' => 'cust_pay',
3049 'hashref' => { 'custnum' => $cust_main->custnum },
3050 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3054 $p->{'amount'} == $cust_pay->paid;
3057 my( $p, $cust_main ) = @_;
3058 $p->{'zip'} eq $cust_main->zip
3059 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3063 foreach my $verify ( split(',', $verification) ) {
3065 &{ $verify{$verify} }( $p, $cust_main )
3066 or return { %$info, 'error' => 'Account not found' };
3070 #okay, we're verified
3074 my $error = $contact->send_reset_email(
3075 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3079 return { %$info, 'error' => $error }; #????
3082 } elsif ( $svc_acct ) {
3084 #create a unique session
3086 my $reset_session = {
3087 'svcnum' => $svc_acct->svcnum,
3091 my $timeout = '1 hour'; #?
3093 my $reset_session_id;
3095 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3096 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3099 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3103 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3104 $cust_main->agentnum);
3105 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3106 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3108 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3109 my $error = $msg_template->send( 'cust_main' => $cust_main,
3110 'object' => $svc_acct,
3111 'substitutions' => {
3112 'session_id' => $reset_session_id,
3116 return { %$info, 'error' => $error }; #????
3121 return { %$info, 'error' => '' };
3124 sub check_reset_passwd {
3127 my $conf = new FS::Conf;
3128 my $verification = $conf->config('selfservice-password_reset_verification')
3129 or return { 'error' => 'Password resets disabled' };
3131 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3132 or return { 'error' => "Can't resume session" }; #better error message
3134 if ( $reset_session->{'svcnum'} ) {
3136 my $svcnum = $reset_session->{'svcnum'};
3138 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3139 or return { 'error' => "Service not found" };
3141 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3142 my $info = skin_info($p);
3146 'session_id' => $p->{'session_id'},
3147 'username' => $svc_acct->username,
3150 } elsif ( $reset_session->{'contactnum'} ) {
3152 my $contactnum = $reset_session->{'contactnum'};
3154 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3155 or return { 'error' => "Contact not found" };
3157 my @contact_email = $contact->contact_email;
3158 return { 'error' => 'No contact email' } unless @contact_email;
3160 $p->{'agentnum'} = $contact->cust_main->agentnum;
3161 my $info = skin_info($p);
3165 'session_id' => $p->{'session_id'},
3166 'email' => $contact_email[0]->email, #the first?
3171 return { 'error' => 'No svcnum or contactnum in session' }; #??
3177 sub process_reset_passwd {
3180 my $conf = new FS::Conf;
3181 my $verification = $conf->config('selfservice-password_reset_verification')
3182 or return { 'error' => 'Password resets disabled' };
3184 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3185 or return { 'error' => "Can't resume session" }; #better error message
3190 if ( $reset_session->{'svcnum'} ) {
3192 my $svcnum = $reset_session->{'svcnum'};
3194 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3195 or return { 'error' => "Service not found" };
3197 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3198 $info ||= skin_info($p);
3203 if ( $reset_session->{'contactnum'} ) {
3205 my $contactnum = $reset_session->{'contactnum'};
3207 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3208 or return { 'error' => "Contact not found" };
3210 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3211 $info ||= skin_info($p);
3215 return { %$info, 'error' => "New passwords don't match." }
3216 if $p->{'new_password'} ne $p->{'new_password2'};
3218 return { %$info, 'error' => 'Enter new password' }
3219 unless length($p->{'new_password'});
3223 $svc_acct->set_password($p->{'new_password'});
3224 my $error = $svc_acct->replace();
3226 return { %$info, 'error' => $error } if $error;
3228 #my($label, $value) = $svc_acct->cust_svc->label;
3229 #return { 'error' => $error,
3230 # #'label' => $label,
3231 # #'value' => $value,
3238 my $error = $contact->change_password($p->{'new_password'});
3240 return { %$info, 'error' => $error }; # if $error;
3244 #password changed ,so remove session, don't want it reused
3245 _cache->remove($p->{'session_id'});
3247 return { %$info, 'error' => '' };
3253 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3254 return { 'error' => $session } if $context eq 'error';
3257 if ( $session->{'pkgnum'} ) {
3259 #tickets for specific service with pkg-balances on
3260 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3261 'pkgnum' => $session->{'pkgnum'} })
3262 or return { 'error' => 'unknown package' };
3263 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3264 push @tickets, $cust_svc->tickets( $p->{status} );
3269 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3270 or return { 'error' => "unknown custnum $custnum" };
3272 @tickets = $cust_main->tickets( $p->{status} );
3275 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3276 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3277 my $conf = new FS::Conf;
3278 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3282 ($a->{'_selfservice_priority'} eq '') <=>
3283 ($b->{'_selfservice_priority'} eq '')
3286 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3292 +{ tickets => \@tickets };
3299 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3300 return { 'error' => $session } if $context eq 'error';
3302 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3303 FS::TicketSystem->init();
3305 my $conf = new FS::Conf;
3306 my $queue = $p->{'queue'}
3307 || $conf->config('ticket_system-selfservice_queueid')
3308 || $conf->config('ticket_system-default_queueid');
3310 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3311 my $err_or_ticket = FS::TicketSystem->create_ticket(
3312 '', #create RT session based on FS CurrentUser (fs_selfservice)
3314 'custnum' => $custnum,
3315 'svcnum' => $session->{'svcnum'},
3316 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3319 if ( ref($err_or_ticket) ) {
3320 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3322 return { 'error' => '',
3323 'ticket_id' => $err_or_ticket->id,
3326 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3328 return { 'error' => $err_or_ticket };
3336 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3337 return { 'error' => $session } if $context eq 'error';
3339 return { error => 'requested format not implemented' }
3340 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3342 my $conf = new FS::Conf;
3343 my $age_threshold = 0;
3344 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3345 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3347 my $search = { 'custnum' => $custnum };
3348 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3349 my $cust_main = qsearchs('cust_main', $search )
3350 or return { 'error' => "unknown custnum $custnum" };
3352 # does it make more sense to just run one sql query for this instead of all the
3353 # insanity below? would increase performance greately for large data sets?
3355 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3356 my @part_svc = $cust_pkg->part_svc;
3357 foreach my $part_svc ( @part_svc ) {
3358 if($part_svc->svcdb eq 'svc_phone'){
3359 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3360 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3361 push @svc_phone, $cust_pkg_svc->svc_x
3362 if $cust_pkg_svc->date_inserted >= $age_threshold;
3370 my($xls_r,$xls_c) = (0,0);
3373 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3374 if($p->{'format'} eq 'csv') {
3375 $csv = new Text::CSV_XS { 'always_quote' => 1,
3378 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3379 $content .= $csv->string;
3381 elsif($p->{'format'} eq 'xls') {
3382 my $XLS1 = new IO::Scalar \$content;
3383 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3384 or return { 'error' => "Error opening .xls file: $!" };
3385 $xls = $xls_workbook->add_worksheet('DIDs');
3386 foreach ( @fields ) {
3387 $xls->write(0,$xls_c++,$_);
3392 foreach my $svc_phone ( @svc_phone ) {
3393 my @cols = map { $svc_phone->$_ } @fields;
3394 if($p->{'format'} eq 'csv') {
3395 return { 'error' => 'Unable to create CSV' }
3396 unless $csv->combine(@cols);
3397 $content .= $csv->string;
3399 elsif($p->{'format'} eq 'xls') {
3402 $xls->write($xls_r,$xls_c++,$_);
3408 $xls_workbook->close() if $p->{'format'} eq 'xls';
3410 { content => $content, format => $p->{'format'}, };
3415 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3416 return { 'error' => $session } if $context eq 'error';
3418 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3419 # FS::TicketSystem->init();
3420 # return { 'error' => 'get_ticket configuration error' }
3421 # if $FS::TicketSystem::system ne 'RT_Internal';
3423 # check existence and ownership as part of this
3424 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3425 my $rt_session = FS::TicketSystem->session('');
3426 my $Ticket = FS::TicketSystem->get_ticket_object(
3428 ticket_id => $p->{'ticket_id'},
3431 return { 'error' => 'ticket not found' } if !$Ticket;
3433 if ( length( $p->{'subject'} || '' ) ) {
3435 if ( $p->{'subject'} ne $Ticket->Subject ) {
3436 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3437 return { 'error' => "unable to set subject: $msg" } if !$val;
3441 if(length($p->{'reply'})) {
3442 my @err_or_res = FS::TicketSystem->correspond_ticket(
3444 'ticket_id' => $p->{'ticket_id'},
3445 'content' => $p->{'reply'},
3448 return { 'error' => 'unable to reply to ticket' }
3449 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3452 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3453 my $err_or_ticket = FS::TicketSystem->get_ticket(
3455 'ticket_id' => $p->{'ticket_id'},
3458 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3459 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3461 return { 'error' => $err_or_ticket };
3464 my @custs = @{$err_or_ticket->{'custs'}};
3465 my @txns = @{$err_or_ticket->{'txns'}};
3468 # superseded by check in get_ticket_object
3469 #return { 'error' => 'invalid ticket requested' }
3470 #unless grep($_ eq $custnum, @custs);
3472 foreach my $txn ( @txns ) {
3473 push @filtered_txns, $txn
3474 if ($txn->{'type'} eq 'EmailRecord'
3475 || $txn->{'type'} eq 'Correspond'
3476 || $txn->{'type'} eq 'Create');
3479 warn "$me get_ticket: successful: \n"
3481 return { 'error' => '',
3482 'transactions' => \@filtered_txns,
3483 'ticket_fields' => $err_or_ticket->{'fields'},
3484 'ticket_id' => $p->{'ticket_id'},
3488 sub adjust_ticket_priority {
3490 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3491 return { 'error' => $session } if $context eq 'error';
3493 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3494 # FS::TicketSystem->init;
3495 my $ss_priority = FS::TicketSystem->selfservice_priority;
3497 return { 'error' => 'adjust_ticket_priority configuration error' }
3498 if $FS::TicketSystem::system ne 'RT_Internal'
3501 my $values = $p->{'values'}; #hashref, id => priority value
3504 foreach my $id (keys %$values) {
3505 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3506 my $Ticket = FS::TicketSystem->get_ticket_object('',
3508 'custnum' => $custnum,
3511 $ticket_error{$id} = 'ticket not found';
3515 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3516 # We're not going to implement it for RT_External.
3517 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3518 my $new_value = $values->{$id};
3519 next if $old_value eq $new_value;
3521 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3523 # AddCustomFieldValue works fine (replacing any existing value) if it's
3524 # a single-valued custom field, which it should be. If it's not, you're
3525 # doing something wrong.
3527 if ( length($new_value) ) {
3528 ($val, $msg) = $Ticket->AddCustomFieldValue(
3529 Field => $ss_priority,
3530 Value => $new_value,
3534 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3535 Field => $ss_priority,
3536 Value => $old_value,
3540 $ticket_error{$id} = $msg if !$val;
3541 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3543 return { 'error' => '',
3544 'ticket_error' => \%ticket_error,
3545 %{ customer_info($p) } # send updated customer info back
3551 sub _custoragent_session_custnum {
3554 my($context, $session, $custnum);
3555 if ( $p->{'session_id'} ) {
3557 $context = 'customer';
3558 $session = _cache->get($p->{'session_id'})
3559 or return ( 'error' => "Can't resume session" ); #better error message
3560 $custnum = $session->{'custnum'};
3562 } elsif ( $p->{'agent_session_id'} ) {
3565 my $agent_cache = new FS::ClientAPI_SessionCache( {
3566 'namespace' => 'FS::ClientAPI::Agent',
3568 $session = $agent_cache->get($p->{'agent_session_id'})
3569 or return ( 'error' => "Can't resume session" ); #better error message
3570 $custnum = $p->{'custnum'};
3574 return ( 'error' => "Can't resume session" ); #better error message
3577 ($context, $session, $custnum);