1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
51 $me = '[FS::ClientAPI::MyAccount]';
53 use vars qw( @cust_main_editable_fields @location_editable_fields );
54 @cust_main_editable_fields = qw(
55 first last company daytime night fax mobile
57 payby payinfo payname paystart_month paystart_year payissue payip
58 ss paytype paystate stateid stateid_state
60 @location_editable_fields = qw(
61 address1 address2 city county state zip country
65 BEGIN { #preload to reduce time customer_info takes
66 if ( $FS::TicketSystem::system ) {
67 warn "$me: initializing ticket system\n" if $DEBUG;
68 FS::TicketSystem->init();
73 $cache ||= new FS::ClientAPI_SessionCache( {
74 'namespace' => 'FS::ClientAPI::MyAccount',
81 my($context, $session, $custnum) = _custoragent_session_custnum($p);
82 #return { 'error' => $session } if $context eq 'error';
85 if ( $context eq 'customer' ) {
87 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
90 $sth->execute($custnum) or die $sth->errstr;
92 $agentnum = $sth->fetchrow_arrayref->[0]
93 or die "no agentnum for custnum $custnum";
95 #} elsif ( $context eq 'agent' ) {
96 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
99 $p->{'agentnum'} = $agentnum;
101 my $conf = new FS::Conf;
103 #false laziness w/Signup.pm
105 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
107 if ( $skin_info_cache_agent ) {
109 warn "$me loading cached skin info for agentnum $agentnum\n"
114 warn "$me populating skin info cache for agentnum $agentnum\n"
117 $skin_info_cache_agent = {
118 'agentnum' => $agentnum,
119 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
120 qw( company_name date_format ) ),
121 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
122 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
123 text_color link_color vlink_color hlink_color alink_color
124 font title_color title_align title_size menu_bgcolor menu_fontsize
127 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
128 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
129 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
131 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
132 qw( title_left_image title_right_image
133 menu_top_image menu_body_image menu_bottom_image
136 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
137 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
138 qw( head body_header body_footer company_address ) ),
139 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
142 services.php Services
143 services.php My Services
144 services_new.php Order a new service
147 personal.php Personal Information
148 password.php Change Password
151 payment_cc.php Credit Card Payment
152 payment_ach.php Electronic Check Payment
153 payment_paypal.php PayPal Payment
154 payment_webpay.php Webpay Payments
157 usage_data.php Data usage
158 usage_cdr.php Call usage
160 tickets.php Help Desk
161 tickets.php Open Tickets
162 tickets_resolved.php Resolved Tickets
163 ticket_create.php Create a new ticket
171 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
175 #{ %$skin_info_cache_agent };
176 $skin_info_cache_agent;
183 my $conf = new FS::Conf;
187 'phone_login' => $conf->exists('selfservice_server-phone_login'),
188 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
189 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
190 'banner_image_md5' =>
191 md5_hex($conf->config_binary('selfservice-login_banner_image')),
198 sub login_banner_image {
200 my $conf = new FS::Conf;
201 my $image = $conf->config_binary('selfservice-login_banner_image');
203 'md5' => md5_hex($image),
208 #false laziness w/FS::ClientAPI::passwd::passwd
212 my $conf = new FS::Conf;
216 if ( $p->{'domain'} eq 'svc_phone'
217 && $conf->exists('selfservice_server-phone_login') ) {
219 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
220 return { error => 'Number not found.' } unless $svc_phone;
223 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
224 #return { error => 'Only primary user may log in.' }
225 # if $conf->exists('selfservice_server-primary_only')
226 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
228 return { error => 'Incorrect PIN.' }
229 unless $svc_phone->check_pin($p->{'password'});
233 } elsif ( $p->{email}
234 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
237 return { error => 'Incorrect contact password.' }
238 unless $contact->authenticate_password($p->{'password'});
240 $session->{'custnum'} = $contact->custnum;
244 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
246 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
247 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
249 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
250 'domsvc' => $svc_domain->svcnum, }
252 return { error => 'User not found.' } unless $svc_acct;
254 if($conf->exists('selfservice_server-login_svcpart')) {
255 my @svcpart = $conf->config('selfservice_server-login_svcpart');
256 my $svcpart = $svc_acct->cust_svc->svcpart;
257 return { error => 'Invalid user.' }
258 unless grep($_ eq $svcpart, @svcpart);
261 return { error => 'Incorrect password.' }
262 unless $svc_acct->check_password($p->{'password'});
270 $session->{'svcnum'} = $svc_x->svcnum;
272 my $cust_svc = $svc_x->cust_svc;
273 my $cust_pkg = $cust_svc->cust_pkg;
275 my $cust_main = $cust_pkg->cust_main;
276 $session->{'custnum'} = $cust_main->custnum;
277 if ( $conf->exists('pkg-balances') ) {
278 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
279 $cust_main->ncancelled_pkgs;
280 $session->{'pkgnum'} = $cust_pkg->pkgnum
281 if scalar(@cust_pkg) > 1;
285 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
286 #return { error => 'Only primary user may log in.' }
287 # if $conf->exists('selfservice_server-primary_only')
288 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
289 my $part_pkg = $cust_pkg->part_pkg;
290 return { error => 'Only primary user may log in.' }
291 if $conf->exists('selfservice_server-primary_only')
292 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
298 $session_id = sha512_hex(time(). {}. rand(). $$)
299 } until ( ! defined _cache->get($session_id) ); #just in case
301 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
302 _cache->set( $session_id, $session, $timeout );
304 return { 'error' => '',
305 'session_id' => $session_id,
311 if ( $p->{'session_id'} ) {
312 _cache->remove($p->{'session_id'});
313 return { %{ skin_info($p) }, 'error' => '' };
315 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
322 my($context, $session, $custnum) = _custoragent_session_custnum($p);
323 return { 'error' => $session } if $context eq 'error';
325 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
326 or return { 'error' => "Service not found" };
328 $session->{'svcnum'} = $svc_acct->svcnum;
330 my $conf = new FS::Conf;
331 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
332 _cache->set( $p->{'session_id'}, $session, $timeout );
334 return { 'error' => '' };
338 sub payment_gateway {
340 # takes a cust_main and a cust_payby entry, returns the payment_gateway
341 my $conf = new FS::Conf;
342 my $cust_main = shift;
343 my $cust_payby = shift;
344 my $gatewaynum = $conf->config('selfservice-payment_gateway');
346 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
347 die "configured gatewaynum $gatewaynum not found!" if !$pg;
351 return '' if ! FS::payby->realtime($cust_payby);
352 my $pg = $cust_main->agent->payment_gateway(
353 'method' => FS::payby->payby2bop($cust_payby),
363 my $conf = new FS::Conf;
365 my $info = skin_info($p);
367 use vars qw( $cust_paybys ); #cache for performance
368 unless ( $cust_paybys ) {
370 my %cust_paybys = map { $_ => 1 }
371 map { FS::payby->payby2payment($_) }
372 $conf->config('signup_server-payby');
374 $cust_paybys = [ keys %cust_paybys ];
377 $info->{'cust_paybys'} = $cust_paybys;
379 my($context, $session, $custnum) = _custoragent_session_custnum($p);
380 return { 'error' => $session } if $context eq 'error';
382 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
383 or return { 'error' => "unknown custnum $custnum" };
385 $info->{'hide_payment_fields'} = [
387 my $pg = payment_gateway($cust_main, $_);
388 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
389 } @{ $info->{cust_paybys} }
392 $info->{'self_suspend_reason'} =
393 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
395 $info->{'edit_ticket_subject'} =
396 $conf->exists('ticket_system-selfservice_edit_subject') &&
397 $cust_main->edit_subject;
399 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
401 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
404 'custnum' => $custnum,
405 'access_pkgnum' => $session->{'pkgnum'},
406 'access_svcnum' => $session->{'svcnum'},
413 my($context, $session, $custnum) = _custoragent_session_custnum($p);
414 return { 'error' => $session } if $context eq 'error';
418 my $conf = new FS::Conf;
419 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
421 # if ( $FS::TicketSystem::system ) {
422 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
423 # FS::TicketSystem->init();
426 if ( $custnum ) { #customer record
428 %return = ( %return, %{ customer_info_short($p) } );
430 #redundant with customer_info_short, but we need it for several things below
431 my $search = { 'custnum' => $custnum };
432 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
433 my $cust_main = qsearchs('cust_main', $search )
434 or return { 'error' => "unknown custnum $custnum" };
436 my $list_tickets = list_tickets($p);
437 $return{'tickets'} = $list_tickets->{'tickets'};
439 if ( $session->{'pkgnum'} ) {
440 #XXX open invoices in the pkg-balances case
444 invnum => $_->invnum,
445 date => time2str("%b %o, %Y", $_->_date),
448 } $cust_main->open_cust_bill;
449 $return{open_invoices} = \@open;
451 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
452 my $sth = dbh->prepare($sql) or die dbh->errstr;
453 $sth->execute($custnum) or die $sth->errstr;
454 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
455 $return{'last_invoice_date_pretty'} =
456 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
459 #customer_info_short always has nobalance on..
460 $return{small_custview} =
461 small_custview( $cust_main,
462 $return{countrydefault},
463 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
466 $return{has_ship_address} = $cust_main->has_ship_address;
467 $return{status} = $cust_main->status;
468 $return{statuscolor} = $cust_main->statuscolor;
470 # compatibility: some places in selfservice use this to determine
471 # if there's a ship address
472 if ( $return{has_ship_address} ) {
473 $return{ship_last} = $cust_main->last;
474 $return{ship_first} = $cust_main->first;
477 if (scalar($conf->config('support_packages'))) {
478 my @support_services = ();
479 foreach ($cust_main->support_services) {
480 my $seconds = $_->svc_x->seconds || 0;
481 my $time_remaining = (($seconds < 0) ? '-' : '' ).
482 int(abs($seconds)/3600)."h".
483 sprintf("%02d",(abs($seconds)%3600)/60)."m";
484 my $cust_pkg = $_->cust_pkg;
487 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
488 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
489 push @support_services, { svcnum => $_->svcnum,
490 time => $time_remaining,
495 $return{support_services} = \@support_services;
498 if ( $conf->config('prepayment_discounts-credit_type') ) {
500 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
503 } elsif ( $session->{'svcnum'} ) { #no customer record
505 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
506 or die "unknown svcnum";
507 $return{name} = $svc_acct->email;
511 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
515 return { 'error' => '',
516 'custnum' => $custnum,
522 sub customer_info_short {
525 my($context, $session, $custnum) = _custoragent_session_custnum($p);
526 return { 'error' => $session } if $context eq 'error';
530 my $conf = new FS::Conf;
532 if ( $custnum ) { #customer record
534 my $search = { 'custnum' => $custnum };
535 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
536 my $cust_main = qsearchs('cust_main', $search )
537 or return { 'error' => "unknown custnum $custnum" };
539 $return{display_custnum} = $cust_main->display_custnum;
541 if ( $session->{'pkgnum'} ) {
542 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
543 #next_bill_date from cust_pkg?
545 $return{balance} = $cust_main->balance;
546 $return{next_bill_date} = $cust_main->next_bill_date;
547 $return{next_bill_date_pretty} =
548 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
552 $return{countrydefault} = scalar($conf->config('countrydefault'));
554 $return{small_custview} =
555 small_custview( $cust_main,
556 $return{countrydefault},
560 $return{first} = $cust_main->first;
561 $return{'last'} = $cust_main->get('last');
562 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
564 $return{payby} = $cust_main->payby;
566 #none of these are terribly expensive if we want 'em...
567 for (@cust_main_editable_fields) {
568 $return{$_} = $cust_main->get($_);
570 #maybe a little more expensive, but it should be cached by now
571 for (@location_editable_fields) {
572 $return{$_} = $cust_main->bill_location->get($_)
573 if $cust_main->bill_locationnum;
574 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
575 if $cust_main->ship_locationnum;
578 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
579 $return{payinfo} = $cust_main->paymask;
580 @return{'month', 'year'} = $cust_main->paydate_monthyear;
583 my @invoicing_list = $cust_main->invoicing_list;
584 $return{'invoicing_list'} =
585 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
586 $return{'postal_invoicing'} =
587 0 < ( grep { $_ eq 'POST' } @invoicing_list );
589 if ( $session->{'svcnum'} ) {
590 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
591 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
592 $return{'svcnum'} = $session->{'svcnum'};
595 } elsif ( $session->{'svcnum'} ) { #no customer record
597 #uuh, not supproted yet... die?
598 return { 'error' => 'customer_info_short not yet supported as agent' };
602 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
606 return { 'error' => '',
607 'custnum' => $custnum,
612 sub billing_history {
615 my($context, $session, $custnum) = _custoragent_session_custnum($p);
616 return { 'error' => $session } if $context eq 'error';
618 return { 'error' => 'No customer' } unless $custnum;
620 my $search = { 'custnum' => $custnum };
621 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
622 my $cust_main = qsearchs('cust_main', $search )
623 or return { 'error' => "unknown custnum $custnum" };
627 if ( $session->{'pkgnum'} ) {
628 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
629 #next_bill_date from cust_pkg?
630 return { 'error' => 'No history for package' };
633 $return{balance} = $cust_main->balance;
634 $return{next_bill_date} = $cust_main->next_bill_date;
635 $return{next_bill_date_pretty} =
636 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
641 my $conf = new FS::Conf;
643 if ( $conf->exists('selfservice-billing_history-line_items') ) {
645 foreach my $cust_bill ( $cust_main->cust_bill ) {
648 'type' => 'Line item',
649 'description' => $_->desc( $cust_main->locale ).
650 ( $_->sdate && $_->edate
651 ? ' '. time2str('%d-%b-%Y', $_->sdate).
652 ' To '. time2str('%d-%b-%Y', $_->edate)
655 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
656 'date' => $cust_bill->_date,
657 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
659 foreach $cust_bill->cust_bill_pkg;
667 'description' => 'Invoice #'. $_->display_invnum,
668 'amount' => sprintf('%.2f', $_->charged ),
670 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
672 foreach $cust_main->cust_bill;
678 'description' => 'Payment', #XXX type
679 'amount' => sprintf('%.2f', 0 - $_->paid ),
681 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
683 foreach $cust_main->cust_pay;
687 'description' => 'Credit', #more info?
688 'amount' => sprintf('%.2f', 0 -$_->amount ),
690 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
692 foreach $cust_main->cust_credit;
696 'description' => 'Refund', #more info? type, like payment?
697 'amount' => $_->refund,
699 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
701 foreach $cust_main->cust_refund;
703 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
705 $return{'history'} = \@history;
713 my $session = _cache->get($p->{'session_id'})
714 or return { 'error' => "Can't resume session" }; #better error message
716 my $custnum = $session->{'custnum'}
717 or return { 'error' => "no customer record" };
719 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
720 or return { 'error' => "unknown custnum $custnum" };
722 my $new = new FS::cust_main { $cust_main->hash };
724 $new->set( $_ => $p->{$_} )
725 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
727 if ( exists($p->{address1}) ) {
728 my $bill_location = FS::cust_location->new({
729 map { $_ => $p->{$_} } @location_editable_fields
731 # if this is unchanged from before, cust_main::replace will ignore it
732 $new->set('bill_location' => $bill_location);
735 if ( exists($p->{ship_address1}) ) {
736 my $ship_location = FS::cust_location->new({
737 map { $_ => $p->{"ship_$_"} } @location_editable_fields
739 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
740 # Selfservice unfortunately tries to indicate "same as billing
741 # address" by sending all fields empty. Did this ever work?
742 $ship_location = $cust_main->bill_location;
744 $new->set('ship_location' => $ship_location);
746 # but if it hasn't been passed in at all, leave ship_location alone--
747 # DON'T change it to match bill_location.
750 if (exists($p->{'payby'})) {
751 $p->{'payby'} =~ /^([A-Z]{4})$/
752 or return { 'error' => "illegal_payby " . $p->{'payby'} };
756 my $conf = new FS::Conf;
758 if ( $payby =~ /^(CARD|DCRD)$/ ) {
760 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
762 if ( $new->payinfo eq $cust_main->paymask ) {
763 $new->payinfo($cust_main->payinfo);
765 $new->payinfo($p->{'payinfo'});
768 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
770 if ( $conf->exists('selfservice-onfile_require_cvv') ){
771 return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
774 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
777 $p->{'payinfo1'} =~ /^([\dx]+)$/
778 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
780 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
781 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
783 $payinfo = $payinfo1. '@'. $payinfo2;
785 $new->payinfo( ($payinfo eq $cust_main->paymask)
786 ? $cust_main->payinfo
790 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
792 } elsif ( $payby =~ /^(BILL)$/ ) {
794 } elsif ( $payby ) { #notyet ready
795 return { 'error' => "unknown payby $payby" };
799 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
800 #false laziness with httemplate/edit/process/cust_main.cgi
801 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
802 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
804 @invoicing_list = $cust_main->invoicing_list;
807 my $error = $new->replace($cust_main, \@invoicing_list);
808 return { 'error' => $error } if $error;
811 return { 'error' => '' };
816 my $session = _cache->get($p->{'session_id'})
817 or return { 'error' => "Can't resume session" }; #better error message
823 my $conf = new FS::Conf;
824 use vars qw($payment_info); #cache for performance
825 unless ( $payment_info ) {
827 my %states = map { $_->state => 1 }
828 qsearch('cust_main_county', {
829 'country' => $conf->config('countrydefault') || 'US'
832 my %cust_paybys = map { $_ => 1 }
833 map { FS::payby->payby2payment($_) }
834 $conf->config('signup_server-payby');
836 my @cust_paybys = keys %cust_paybys;
840 #list all counties/states/countries
841 'cust_main_county' =>
842 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
844 #shortcut for one-country folks
846 [ sort { $a cmp $b } keys %states ],
848 'card_types' => card_types(),
850 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
851 'require_cvv' => $conf->exists('selfservice-require_cvv'),
852 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
854 'paytypes' => [ @FS::cust_main::paytypes ],
856 'paybys' => [ $conf->config('signup_server-payby') ],
857 'cust_paybys' => \@cust_paybys,
859 'stateid_label' => FS::Msgcat::_gettext('stateid'),
860 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
862 'show_ss' => $conf->exists('show_ss'),
863 'show_stateid' => $conf->exists('show_stateid'),
864 'show_paystate' => $conf->exists('show_bankstate'),
866 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
868 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
877 my %return = %$payment_info;
879 my $custnum = $session->{'custnum'};
881 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
882 or return { 'error' => "unknown custnum $custnum" };
884 $return{'hide_payment_fields'} = [
886 my $pg = payment_gateway($cust_main, $_);
887 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
888 } @{ $return{cust_paybys} }
891 $return{balance} = $cust_main->balance; #XXX pkg-balances?
893 $return{payname} = $cust_main->payname
894 || ( $cust_main->first. ' '. $cust_main->get('last') );
896 $return{$_} = $cust_main->bill_location->get($_)
897 for qw(address1 address2 city state zip);
899 $return{payby} = $cust_main->payby;
900 $return{stateid_state} = $cust_main->stateid_state;
902 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
903 $return{card_type} = cardtype($cust_main->payinfo);
904 $return{payinfo} = $cust_main->paymask;
906 @return{'month', 'year'} = $cust_main->paydate_monthyear;
910 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
911 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
912 $return{payinfo1} = $payinfo1;
913 $return{payinfo2} = $payinfo2;
914 $return{paytype} = $cust_main->paytype;
915 $return{paystate} = $cust_main->paystate;
916 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
919 if ( $conf->config('prepayment_discounts-credit_type') ) {
921 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
924 #doubleclick protection
926 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
927 $return{paybatch} = $return{payunique}; #back compat
929 return { 'error' => '',
935 #some false laziness with httemplate/process/payment.cgi - look there for
936 #ACH and CVV support stuff
938 sub validate_payment {
941 my $session = _cache->get($p->{'session_id'})
942 or return { 'error' => "Can't resume session" }; #better error message
944 my $custnum = $session->{'custnum'};
946 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
947 or return { 'error' => "unknown custnum $custnum" };
949 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
950 or return { 'error' => gettext('illegal_amount') };
952 return { error => 'Amount must be greater than 0' } unless $amount > 0;
954 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
955 #changing the hidden form values
956 my $conf = new FS::Conf;
957 my $fee_display = $conf->config('selfservice_process-display') || 'add';
958 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
959 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
960 if ( $fee_display eq 'add'
962 and ! $fee_skip_first || scalar($cust_main->cust_pay)
965 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
966 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
969 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
970 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
971 my $discount_term = $1;
973 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
974 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
977 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
978 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
981 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
982 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
985 $payunique = $paybatch if ! length($payunique) && length($paybatch);
987 $p->{'payby'} ||= 'CARD';
988 $p->{'payby'} =~ /^([A-Z]{4})$/
989 or return { 'error' => "illegal_payby " . $p->{'payby'} };
992 #false laziness w/process/payment.cgi
995 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
997 $p->{'payinfo1'} =~ /^([\dx]+)$/
998 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1000 $p->{'payinfo2'} =~ /^([\dx]+)$/
1001 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1003 $payinfo = $payinfo1. '@'. $payinfo2;
1005 $payinfo = $cust_main->payinfo
1006 if $cust_main->paymask eq $payinfo;
1008 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1010 $payinfo = $p->{'payinfo'};
1014 #more intelligent matching will be needed here if you change
1015 #card_masking_method and don't remove existing paymasks
1016 if ( $cust_main->paymask eq $payinfo ) {
1017 $payinfo = $cust_main->payinfo;
1021 $payinfo =~ s/\D//g;
1022 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1023 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1027 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1028 return { 'error' => gettext('unknown_card_type') }
1029 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1031 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1032 if ( cardtype($payinfo) eq 'American Express card' ) {
1033 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1034 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1037 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1038 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1041 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1042 return { 'error' => 'CVV2 is required' };
1043 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1044 return { 'error' => 'CVV2 is required' };
1048 die "unknown payby $payby";
1051 my %payby2fields = (
1052 'CARD' => [ qw( paystart_month paystart_year payissue payip
1053 address1 address2 city state zip country ) ],
1054 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1058 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1061 'cust_main' => $cust_main, #XXX or just custnum??
1062 'amount' => sprintf('%.2f', $amount),
1064 'payinfo' => $payinfo,
1065 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1066 'card_type' => $card_type,
1067 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1068 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1069 'month' => $p->{'month'},
1070 'year' => $p->{'year'},
1071 'payname' => $payname,
1072 'payunique' => $payunique,
1073 'paybatch' => $paybatch,
1074 'paycvv' => $paycvv,
1075 'payname' => $payname,
1076 'discount_term' => $discount_term,
1077 'pkgnum' => $session->{'pkgnum'},
1078 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1088 my $validate = validate_payment($p);
1089 return $validate if $validate->{'error'};
1091 my $conf = new FS::Conf;
1092 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1093 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1095 +{ map { $_=>$validate->{$_} }
1096 qw( card_type paymask payname paydate_pretty month year amount
1097 address1 address2 city state zip country
1103 sub process_stored_payment {
1106 my $session_id = $p->{'session_id'};
1108 my $payment_info = _cache->get( "payment_$session_id" )
1109 or return { 'error' => "Can't resume session" }; #better error message
1111 do_process_payment($payment_info);
1115 sub process_payment {
1118 my $payment_info = validate_payment($p);
1119 return $payment_info if $payment_info->{'error'};
1121 do_process_payment($payment_info);
1125 sub do_process_payment {
1126 my $validate = shift;
1128 my $cust_main = $validate->{'cust_main'};
1130 my $amount = delete $validate->{'amount'};
1133 my $payby = delete $validate->{'payby'};
1135 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1138 'paynum_ref' => \$paynum,
1141 return { 'error' => $error } if $error;
1143 #no error, so order the fee package if applicable...
1144 my $conf = new FS::Conf;
1145 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1146 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1148 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1150 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1152 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1153 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1156 #and generate an invoice for it now too
1157 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1158 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1163 $cust_main->apply_payments;
1165 if ( $validate->{'save'} ) {
1166 my $new = new FS::cust_main { $cust_main->hash };
1167 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1168 $new->set( $_ => $validate->{$_} )
1169 foreach qw( payname paystart_month paystart_year payissue payip );
1170 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1172 my $bill_location = FS::cust_location->new({
1173 map { $_ => $validate->{$_} }
1174 qw(address1 address2 city state country zip)
1176 $new->set('bill_location' => $bill_location);
1177 # but don't allow the service address to change this way.
1179 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1180 $new->set( $_ => $validate->{$_} )
1181 foreach qw( payname payip paytype paystate
1182 stateid stateid_state );
1183 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1185 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1186 $new->set( 'paydate' => $validate->{'paydate'} );
1187 my $error = $new->replace($cust_main);
1189 #no, this causes customers to process their payments again
1190 #return { 'error' => $error };
1191 #XXX just warn verosely for now so i can figure out how these happen in
1192 # the first place, eventually should redirect them to the "change
1193 #address" page but indicate the payment did process??
1194 delete($validate->{'payinfo'}); #don't want to log this!
1195 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1196 "NEW: ". Dumper($new)."\n".
1197 "OLD: ". Dumper($cust_main)."\n".
1198 "PACKET: ". Dumper($validate)."\n";
1206 my $receipt_html = '';
1208 # currently supported for realtime CC only; send receipt data to SS
1209 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1212 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1215 <TD ALIGN="right">Payment#</TD>
1216 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1220 <TD ALIGN="right">Date</TD>
1222 <TD BGCOLOR="#FFFFFF"><B>! .
1223 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1229 <TD ALIGN="right">Amount</TD>
1230 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1235 <TD ALIGN="right">Payment method</TD>
1236 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1249 'amount' => sprintf('%.2f', $cust_pay->paid),
1250 'date' => $cust_pay->_date,
1251 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1252 'time_pretty' => time2str('%T', $cust_pay->_date),
1253 'auth_num' => $cust_pay->auth,
1254 'order_num' => $cust_pay->order_number,
1255 'receipt_html' => $receipt_html,
1262 'receipt_html' => '',
1269 sub realtime_collect {
1272 my $session = _cache->get($p->{'session_id'})
1273 or return { 'error' => "Can't resume session" }; #better error message
1275 my $custnum = $session->{'custnum'};
1277 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1278 or return { 'error' => "unknown custnum $custnum" };
1281 if ( $p->{'amount'} ) {
1282 $amount = $p->{'amount'};
1284 elsif ( $session->{'pkgnum'} ) {
1285 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1288 $amount = $cust_main->balance;
1291 my $error = $cust_main->realtime_collect(
1292 'method' => $p->{'method'},
1293 'amount' => $amount,
1294 'pkgnum' => $session->{'pkgnum'},
1295 'session_id' => $p->{'session_id'},
1299 return { 'error' => $error } unless ref( $error );
1301 return { 'error' => '', amount => $amount, %$error };
1304 sub start_thirdparty {
1306 my $session = _cache->get($p->{'session_id'})
1307 or return { 'error' => "Can't resume session" }; #better error message
1308 my $custnum = $session->{'custnum'};
1309 my $cust_main = FS::cust_main->by_key($custnum);
1311 my $amount = $p->{'amount'}
1312 or return { error => 'no amount' };
1314 my $result = $cust_main->create_payment(
1315 'method' => $p->{'method'},
1316 'amount' => $p->{'amount'},
1317 'pkgnum' => $session->{'pkgnum'},
1318 'session_id' => $p->{'session_id'},
1321 if ( ref($result) ) { # hashref or error
1324 return { error => $result };
1328 sub finish_thirdparty {
1330 my $session_id = delete $p->{'session_id'};
1331 my $session = _cache->get($session_id)
1332 or return { 'error' => "Can't resume session" };
1333 my $custnum = $session->{'custnum'};
1334 my $cust_main = FS::cust_main->by_key($custnum);
1336 if ( $p->{_cancel} ) {
1337 # customer backed out of making a payment
1338 return $cust_main->cancel_payment( $session_id );
1340 my $result = $cust_main->execute_payment( $session_id, %$p );
1341 if ( ref($result) ) {
1344 return { error => $result };
1348 sub process_payment_order_pkg {
1351 my $hr = process_payment($p);
1352 return $hr if $hr->{'error'};
1357 sub process_payment_order_renew {
1360 my $hr = process_payment($p);
1361 return $hr if $hr->{'error'};
1366 sub process_prepay {
1370 my $session = _cache->get($p->{'session_id'})
1371 or return { 'error' => "Can't resume session" }; #better error message
1375 my $custnum = $session->{'custnum'};
1377 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1378 or return { 'error' => "unknown custnum $custnum" };
1380 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1381 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1389 return { 'error' => $error } if $error;
1391 return { 'error' => '',
1392 'amount' => $amount,
1393 'seconds' => $seconds,
1394 'duration' => duration_exact($seconds),
1395 'upbytes' => $upbytes,
1396 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1397 'downbytes' => $downbytes,
1398 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1399 'totalbytes'=> $totalbytes,
1400 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1407 my $session = _cache->get($p->{'session_id'})
1408 or return { 'error' => "Can't resume session" }; #better error message
1410 my $custnum = $session->{'custnum'};
1412 my $invnum = $p->{'invnum'};
1414 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1415 'custnum' => $custnum } )
1416 or return { 'error' => "Can't find invnum" };
1420 return { 'error' => '',
1421 'invnum' => $invnum,
1422 'invoice_text' => join('', $cust_bill->print_text ),
1423 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1430 my $session = _cache->get($p->{'session_id'})
1431 or return { 'error' => "Can't resume session" }; #better error message
1433 my $custnum = $session->{'custnum'};
1435 my $invnum = $p->{'invnum'};
1437 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1438 'custnum' => $custnum } )
1439 or return { 'error' => "Can't find invnum" };
1443 return { 'error' => '',
1444 'invnum' => $invnum,
1445 'invoice_pdf' => $cust_bill->print_pdf({
1446 'unsquelch_cdr' => 1,
1447 'locale' => $p->{'locale'},
1453 sub legacy_invoice {
1455 my $session = _cache->get($p->{'session_id'})
1456 or return { 'error' => "Can't resume session" }; #better error message
1458 my $custnum = $session->{'custnum'};
1460 my $legacyinvnum = $p->{'legacyinvnum'};
1463 'legacyinvnum' => $legacyinvnum,
1464 'custnum' => $custnum,
1467 my $legacy_cust_bill =
1468 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1469 || qsearchs('legacy_cust_bill', \%hash )
1470 or return { 'error' => "Can't find legacyinvnum" };
1474 return { 'error' => '',
1475 'legacyinvnum' => $legacyinvnum,
1476 'legacyid' => $legacy_cust_bill->legacyid,
1477 'invoice_html' => $legacy_cust_bill->content_html,
1482 sub legacy_invoice_pdf {
1484 my $session = _cache->get($p->{'session_id'})
1485 or return { 'error' => "Can't resume session" }; #better error message
1487 my $custnum = $session->{'custnum'};
1489 my $legacyinvnum = $p->{'legacyinvnum'};
1491 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1492 'legacyinvnum' => $legacyinvnum,
1493 'custnum' => $custnum,
1494 }) or return { 'error' => "Can't find legacyinvnum" };
1498 return { 'error' => '',
1499 'legacyinvnum' => $legacyinvnum,
1500 'legacyid' => $legacy_cust_bill->legacyid,
1501 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1509 #sessioning for this? how do we get the session id to the backend invoice
1510 # template so it can add it to the link, blah
1513 if ( $p->{'invnum'} ) {
1514 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1515 or return { 'error' => 'unknown invnum' };
1516 $agentnum = $cust_bill->cust_main->agentnum;
1519 my $templatename = $p->{'template'} || $p->{'templatename'};
1521 #false laziness-ish w/view/cust_bill-logo.cgi
1523 my $conf = new FS::Conf;
1524 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1525 $templatename = "_$1";
1530 my $filename = "logo$templatename.png";
1532 return { 'error' => '',
1533 'logo' => $conf->config_binary($filename, $agentnum),
1534 'content_type' => 'image/png', #should allow gif, jpg too
1541 my $session = _cache->get($p->{'session_id'})
1542 or return { 'error' => "Can't resume session" }; #better error message
1544 my $custnum = $session->{'custnum'};
1546 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1547 or return { 'error' => "unknown custnum $custnum" };
1549 my $conf = new FS::Conf;
1551 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1553 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1557 return { 'error' => '',
1558 'balance' => $cust_main->balance,
1561 my $owed = $_->owed;
1563 +{ 'invnum' => $_->invnum,
1564 '_date' => $_->_date,
1565 'date' => time2str("%b %o, %Y", $_->_date),
1566 'date_short' => time2str("%m-%d-%Y", $_->_date),
1567 'previous' => sprintf('%.2f', ($_->previous)[0]),
1568 'charged' => sprintf('%.2f', $_->charged),
1569 'owed' => sprintf('%.2f', $owed),
1570 'balance' => sprintf('%.2f', $balance),
1575 'legacy_invoices' => [
1577 +{ 'legacyinvnum' => $_->legacyinvnum,
1578 'legacyid' => $_->legacyid,
1579 '_date' => $_->_date,
1580 'date' => time2str("%b %o, %Y", $_->_date),
1581 'date_short' => time2str("%m-%d-%Y", $_->_date),
1582 'charged' => sprintf('%.2f', $_->charged),
1583 'has_content' => ( length($_->content_pdf)
1584 || length($_->content_html) ),
1594 my $session = _cache->get($p->{'session_id'})
1595 or return { 'error' => "Can't resume session" }; #better error message
1597 my $custnum = $session->{'custnum'};
1599 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1600 or return { 'error' => "unknown custnum $custnum" };
1602 my @errors = $cust_main->cancel( 'quiet'=>1 );
1604 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1606 return { 'error' => $error };
1613 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1614 return { 'error' => $session } if $context eq 'error';
1616 my $search = { 'custnum' => $custnum };
1617 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1618 my $cust_main = qsearchs('cust_main', $search )
1619 or return { 'error' => "unknown custnum $custnum" };
1621 my $conf = new FS::Conf;
1622 my $immutable = $conf->exists('selfservice_immutable-package');
1624 # the duplication below is necessary:
1625 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1626 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1627 # non-backwards-compatible change breaking the software of anyone using the API
1628 # instead of the stock selfservice
1629 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1630 if( $conf->exists('selfservice_server-view-wholesale') ) {
1631 return { 'svcnum' => $session->{'svcnum'},
1632 'custnum' => $custnum,
1633 'cust_pkg' => [ map {
1635 immutable => $immutable,
1636 part_pkg => [ map $_->hashref, $_->part_pkg ],
1638 [ map $_->hashref, $_->available_part_svc ],
1640 [ map { my $ref = { $_->hash,
1641 label => [ $_->label ],
1643 $ref->{_password} = $_->svc_x->_password
1644 if $context eq 'agent'
1645 && $conf->exists('agent-showpasswords')
1646 && $_->part_svc->svcdb eq 'svc_acct';
1651 } $cust_main->cust_pkg
1654 small_custview( $cust_main, $conf->config('countrydefault') ),
1655 'wholesale_view' => 1,
1656 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1657 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1658 'lnp' => $conf->exists('svc_phone-lnp'),
1662 { 'svcnum' => $session->{'svcnum'},
1663 'custnum' => $custnum,
1664 'cust_pkg' => [ map {
1665 my $primary_cust_svc = $_->primary_cust_svc;
1668 immutable => $immutable,
1669 pkg_label => $_->pkg_locale,
1670 status => $_->status,
1671 statuscolor => $_->statuscolor,
1673 [ map { $_->hashref }
1674 grep { $_->selfservice_access ne 'hidden' }
1675 $_->available_part_svc
1678 [ map { my $ref = { $_->hash,
1679 label => [ $_->label ],
1681 $ref->{_password} = $_->svc_x->_password
1682 if $context eq 'agent'
1683 && $conf->exists('agent-showpasswords')
1684 && $_->part_svc->svcdb eq 'svc_acct';
1685 $ref->{svchash} = { $_->svc_x->hash } if
1686 $_->part_svc->svcdb eq 'svc_phone';
1687 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1688 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1691 grep { $_->part_svc->selfservice_access ne 'hidden' }
1696 ? { $primary_cust_svc->hash,
1697 label => [ $primary_cust_svc->label ],
1698 finger => $primary_cust_svc->svc_x->finger, #uuh
1699 $primary_cust_svc->part_svc->hash,
1703 } $cust_main->ncancelled_pkgs
1706 small_custview( $cust_main, $conf->config('countrydefault') ),
1707 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1715 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1716 return { 'error' => $session } if $context eq 'error';
1718 my $search = { 'custnum' => $custnum };
1719 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1720 my $cust_main = qsearchs('cust_main', $search )
1721 or return { 'error' => "unknown custnum $custnum" };
1723 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1724 if ( ! $pkgnum && $p->{'svcnum'} ) {
1725 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1726 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1730 my @cust_pkg_usage = ();
1731 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1732 foreach my $cust_pkg ( $p->{'ncancelled'}
1733 ? $cust_main->ncancelled_pkgs
1734 : $cust_main->unsuspended_pkgs ) {
1735 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1736 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1737 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1740 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1742 foreach (@cust_pkg_usage) {
1743 my $part = $_->part_pkg_usage;
1744 my $tag = $part->description . ($part->shared ? 1 : 0);
1745 my $row = $usage_pools{$tag}
1746 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1747 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1748 $row->[2] += $part->minutes; # minutes total
1751 if ( $p->{'svcdb'} ) {
1752 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1754 : ref($p->{'svcdb'}) eq 'ARRAY'
1755 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1756 : { $p->{'svcdb'} => 1 };
1757 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1760 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1763 my $conf = new FS::Conf;
1766 'svcnum' => $session->{'svcnum'},
1767 'custnum' => $custnum,
1768 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1769 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1772 my $svc_x = $_->svc_x;
1773 my($label, $value) = $_->label;
1774 my $part_svc = $_->part_svc;
1775 my $svcdb = $part_svc->svcdb;
1776 my $cust_pkg = $_->cust_pkg;
1777 my $part_pkg = $cust_pkg->part_pkg;
1780 'svcnum' => $_->svcnum,
1781 'display_svcnum' => $_->display_svcnum,
1785 'pkg_label' => $cust_pkg->pkg_locale,
1786 'pkg_status' => $cust_pkg->status,
1787 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1790 if ( $svcdb eq 'svc_acct' ) {
1793 'username' => $svc_x->username,
1794 'email' => $svc_x->email,
1795 'finger' => $svc_x->finger,
1796 'seconds' => $svc_x->seconds,
1797 'upbytes' => display_bytecount($svc_x->upbytes),
1798 'downbytes' => display_bytecount($svc_x->downbytes),
1799 'totalbytes' => display_bytecount($svc_x->totalbytes),
1801 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1802 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1803 'recharge_upbytes' =>
1804 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1805 'recharge_downbytes' =>
1806 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1807 'recharge_totalbytes' =>
1808 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1812 } elsif ( $svcdb eq 'svc_dsl' ) {
1813 $hash{'phonenum'} = $svc_x->phonenum;
1814 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1815 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1816 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1819 $hash{'name'} = $cust_main->name;
1821 } elsif ( $svcdb eq 'svc_phone' ) {
1822 # could potentially show lots of things...
1823 $hash{'outbound'} = 1;
1824 $hash{'inbound'} = 0;
1825 if ( $part_pkg->plan eq 'voip_inbound' ) {
1826 $hash{'outbound'} = 0;
1827 $hash{'inbound'} = 1;
1828 } elsif ( $part_pkg->option('selfservice_inbound_format')
1829 or $conf->config('selfservice-default_inbound_cdr_format')
1831 $hash{'inbound'} = 1;
1833 foreach (qw(inbound outbound)) {
1834 # hmm...we can't filter by status here, because there might
1835 # not be cdr_terminations at all. have to go by date.
1836 # find all since the last bill date.
1837 # XXX cdr types? we are going to need them.
1839 my $sum_cdr = $svc_x->sum_cdrs(
1840 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1841 'begin' => ($cust_pkg->last_bill || 0),
1843 'disable_charged_party' => 1,
1845 $hash{$_} = $sum_cdr->hashref;
1850 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1861 map { $usage_pools{$_} }
1869 sub _customer_svc_x {
1870 my($custnum, $svcnum, $table) = (shift, shift, shift);
1871 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1873 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1874 my $search = " AND custnum = $1";
1875 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1878 'table' => ($table || 'svc_acct'),
1879 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1880 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1881 #'LEFT JOIN cust_main USING ( custnum ) ',
1882 'hashref' => $hashref,
1883 'extra_sql' => $search, #important
1888 sub svc_status_html {
1891 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1892 return { 'error' => $session } if $context eq 'error';
1894 #XXX only svc_dsl for now
1895 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1896 or return { 'error' => "Service not found" };
1898 my $html = $svc_x->getstatus_html;
1900 return { 'html' => $html };
1904 sub svc_status_hash {
1907 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1908 return { 'error' => $session } if $context eq 'error';
1910 #XXX only svc_acct for now
1911 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1912 or return { 'error' => "Service not found" };
1914 my ( $html, $hashref ) = $svc_x->export_getstatus;
1919 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1920 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1921 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1922 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1923 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1926 my( $p, $method ) = @_;
1928 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1929 return { 'error' => $session } if $context eq 'error';
1931 #XXX only svc_acct for now
1932 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1933 or return { 'error' => "Service not found" };
1935 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1937 my $error = $svc_x->$method($p); #$p? returns error?
1938 return { 'error' => $error } if $error;
1940 return {}; #? { 'error' => '' }
1944 sub acct_forward_info {
1947 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1948 return { 'error' => $session } if $context eq 'error';
1950 my $svc_forward = _customer_svc_x( $custnum,
1951 { 'srcsvc' => $p->{'svcnum'} },
1954 or return { 'error' => '',
1958 return { 'error' => '',
1959 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1964 sub process_acct_forward {
1966 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1967 return { 'error' => $session } if $context eq 'error';
1969 my $old = _customer_svc_x( $custnum,
1970 { 'srcsvc' => $p->{'svcnum'} },
1974 if ( $p->{'dst'} eq '' ) {
1976 my $error = $old->delete;
1977 return { 'error' => $error };
1979 return { 'error' => '' };
1982 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1983 'dst' => $p->{'dst'},
1988 $new->svcnum($old->svcnum);
1989 my $cust_svc = $old->cust_svc;
1990 $new->svcpart($old->svcpart);
1991 $new->pkgnuym($old->pkgnum);
1992 $error = $new->replace($old);
1994 my $conf = new FS::Conf;
1995 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1997 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1998 or return { 'error' => 'No service' }; #how would we even get here?
2000 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2002 $error = $new->insert;
2005 return { 'error' => $error };
2009 sub list_dsl_devices {
2012 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2013 return { 'error' => $session } if $context eq 'error';
2015 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2016 or return { 'error' => "Service not found" };
2019 'devices' => [ map {
2020 +{ 'mac_addr' => $_->mac_addr };
2021 } $svc_dsl->dsl_device
2027 sub add_dsl_device {
2030 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2031 return { 'error' => $session } if $context eq 'error';
2033 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2034 or return { 'error' => "Service not found" };
2036 return { 'error' => 'No MAC address supplied' }
2037 unless length($p->{'mac_addr'});
2039 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2040 'mac_addr' => scalar($p->{'mac_addr'}),
2042 my $error = $dsl_device->insert;
2043 return { 'error' => $error };
2047 sub delete_dsl_device {
2050 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2051 return { 'error' => $session } if $context eq 'error';
2053 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2054 or return { 'error' => "Service not found" };
2056 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2057 'mac_addr' => scalar($p->{'mac_addr'}),
2060 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2062 my $error = $dsl_device->delete;
2063 return { 'error' => $error };
2069 _usage_details( \&_port_graph, $p,
2070 'svcdb' => 'svc_port',
2075 my($svc_port, $begin, $end) = @_;
2077 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2078 push @usage, { 'png' => $pngOrError };
2082 sub _list_svc_usage {
2083 my($svc_acct, $begin, $end) = @_;
2085 foreach my $part_export (
2086 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2087 qw( sqlradius sqlradius_withdomain )
2089 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2094 sub list_svc_usage {
2095 _usage_details(\&_list_svc_usage, @_);
2098 sub _list_support_usage {
2099 my($svc_acct, $begin, $end) = @_;
2101 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2102 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2104 push @usage, { 'seconds' => $_->seconds,
2105 'support' => $_->support,
2106 '_date' => $_->_date,
2107 'id' => $_->transaction_id,
2108 'creator' => $_->creator,
2109 'subject' => $_->subject,
2110 'status' => $_->status,
2111 'ticketid' => $_->ticketid,
2117 sub list_support_usage {
2118 _usage_details(\&_list_support_usage, @_);
2121 sub _list_cdr_usage {
2122 # XXX CDR type support...
2123 # XXX any way to do a paged search on this?
2124 # we have to return the results all at once...
2125 my($svc_phone, $begin, $end, %opt) = @_;
2126 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2127 $svc_phone->get_cdrs(
2130 'disable_charged_party' => 1,
2135 sub list_cdr_usage {
2137 _usage_details( \&_list_cdr_usage, $p,
2138 'svcdb' => 'svc_phone',
2142 sub _usage_details {
2143 my($callback, $p, %opt) = @_;
2144 my $conf = FS::Conf->new;
2146 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2147 return { 'error' => $session } if $context eq 'error';
2149 my $search = { 'svcnum' => $p->{'svcnum'} };
2150 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2152 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2154 my $svc_x = qsearchs( $svcdb, $search );
2155 return { 'error' => 'No service selected in list_svc_usage' }
2158 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2159 my $freq = $cust_pkg->part_pkg->freq;
2162 if ( $svcdb eq 'svc_phone' ) {
2164 if ( $p->{inbound} ) {
2165 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2166 || $conf->config('selfservice-default_inbound_cdr_format')
2167 || 'source_default';
2168 $callback_opt{inbound} = 1;
2170 $format = $cust_pkg->part_pkg->option('selfservice_format')
2171 || $conf->config('selfservice-default_cdr_format')
2175 $callback_opt{format} = $format;
2176 $callback_opt{use_clid} = 1;
2177 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2180 my $start = $cust_pkg->setup;
2181 #my $end = $cust_pkg->bill; # or time?
2184 unless ( $p->{beginning} ) {
2185 $p->{beginning} = $cust_pkg->last_bill;
2186 $p->{ending} = $end;
2189 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2190 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2192 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2196 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2197 # ugly kludge, I know
2198 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2199 if (defined $delete_col) {
2200 delete($_->[$delete_col]) foreach ($header, @usage);
2204 #kinda false laziness with FS::cust_main::bill, but perhaps
2205 #we should really change this bit to DateTime and DateTime::Duration
2207 #change this bit to use Date::Manip? CAREFUL with timezones (see
2208 # mailing list archive)
2209 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2210 (localtime($p->{ending}) )[0,1,2,3,4,5];
2211 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2212 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2214 if ( $freq =~ /^\d+$/ ) {
2216 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2218 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2219 } elsif ( $freq =~ /^(\d+)w$/ ) {
2221 $nmday += $weeks * 7;
2222 $pmday -= $weeks * 7;
2223 } elsif ( $freq =~ /^(\d+)d$/ ) {
2227 } elsif ( $freq =~ /^(\d+)h$/ ) {
2232 return { 'error' => "unparsable frequency: ". $freq };
2235 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2236 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2240 'svcnum' => $p->{svcnum},
2241 'beginning' => $p->{beginning},
2242 'ending' => $p->{ending},
2243 'inbound' => $p->{inbound},
2244 'previous' => ($previous > $start) ? $previous : $start,
2245 'next' => ($next < $end) ? $next : $end,
2246 'header' => $header,
2254 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2255 return { 'error' => $session } if $context eq 'error';
2257 my $search = { 'custnum' => $custnum };
2258 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2259 my $cust_main = qsearchs('cust_main', $search )
2260 or return { 'error' => "unknown custnum $custnum" };
2262 my $status = $cust_main->status;
2263 #false laziness w/ClientAPI/Signup.pm
2265 my $cust_pkg = new FS::cust_pkg ( {
2266 'custnum' => $custnum,
2267 'pkgpart' => $p->{'pkgpart'},
2269 my $error = $cust_pkg->check;
2270 return { 'error' => $error } if $error;
2273 unless ( $p->{'svcpart'} eq 'none' ) {
2277 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2279 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2280 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2281 $svcdb = $part_svc->svcdb;
2283 $svcdb = 'svc_acct';
2285 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2288 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2289 'svc_domain' => [ qw( domain ) ],
2290 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2291 'svc_external' => [ qw( id title ) ],
2292 'svc_pbx' => [ qw( id title ) ],
2295 my $svc_x = "FS::$svcdb"->new( {
2296 'svcpart' => $svcpart,
2297 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2300 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2303 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2304 my $acct_snarf = new FS::acct_snarf ( {
2305 'machine' => $p->{"snarf_machine$snarfnum"},
2306 'protocol' => $p->{"snarf_protocol$snarfnum"},
2307 'username' => $p->{"snarf_username$snarfnum"},
2308 '_password' => $p->{"snarf_password$snarfnum"},
2311 push @acct_snarf, $acct_snarf;
2313 $svc_x->child_objects( \@acct_snarf );
2316 my $y = $svc_x->setdefault; # arguably should be in new method
2317 return { 'error' => $y } if $y && !ref($y);
2319 $error = $svc_x->check;
2320 return { 'error' => $error } if $error;
2327 tie my %hash, 'Tie::RefHash';
2328 %hash = ( $cust_pkg => \@svc );
2330 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2331 return { 'error' => $error } if $error;
2333 my $conf = new FS::Conf;
2334 if ( $conf->exists('signup_server-realtime') ) {
2336 my $bill_error = _do_bop_realtime( $cust_main, $status );
2339 $cust_pkg->cancel('quiet'=>1);
2342 $cust_pkg->reexport;
2346 $cust_pkg->reexport;
2349 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2351 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2358 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2359 return { 'error' => $session } if $context eq 'error';
2361 my $conf = new FS::Conf;
2362 my $immutable = $conf->exists('selfservice_immutable-package');
2363 return { 'error' => "Package modification disabled" } if $immutable;
2365 my $search = { 'custnum' => $custnum };
2366 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2367 my $cust_main = qsearchs('cust_main', $search )
2368 or return { 'error' => "unknown custnum $custnum" };
2370 my $status = $cust_main->status;
2371 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2372 or return { 'error' => "unknown package $p->{pkgnum}" };
2374 #if someone does need self-service package change of suspended packages,
2375 # figure out how to be more discriminating
2376 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2377 if $cust_pkg->status eq 'suspended';
2380 my $error = FS::cust_pkg::order( $custnum,
2386 if ( $conf->exists('signup_server-realtime') ) {
2388 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2391 $newpkg[0]->suspend;
2394 $newpkg[0]->reexport;
2398 $newpkg[0]->reexport;
2401 return { error => '', pkgnum => $cust_pkg->pkgnum };
2405 sub order_recharge {
2408 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2409 return { 'error' => $session } if $context eq 'error';
2411 my $search = { 'custnum' => $custnum };
2412 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2413 my $cust_main = qsearchs('cust_main', $search )
2414 or return { 'error' => "unknown custnum $custnum" };
2416 my $status = $cust_main->status;
2417 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2418 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2420 my $svc_x = $cust_svc->svc_x;
2421 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2424 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2425 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2426 recharge_totalbytes );
2427 my $amount = $part_pkg->option('recharge_amount', 1);
2429 my ($l, $v, $d) = $cust_svc->label; # blah
2430 my $pkg = "Recharge $v";
2432 my $bill_error = $cust_main->charge($amount, $pkg,
2433 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2434 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2435 $part_pkg->taxclass); #meh
2437 my $conf = new FS::Conf;
2438 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2440 $bill_error = _do_bop_realtime( $cust_main, $status );
2445 my $error = $svc_x->recharge (\%vhash);
2446 return { 'error' => $error } if $error;
2450 my $error = $bill_error;
2451 $error ||= $svc_x->recharge (\%vhash);
2452 return { 'error' => $error } if $error;
2455 return { error => '', svc => $cust_svc->part_svc->svc };
2459 sub _do_bop_realtime {
2460 my ($cust_main, $status, %opt) = @_;
2462 my $old_balance = $cust_main->balance;
2464 my $bill_error = $cust_main->bill
2465 || $cust_main->apply_payments_and_credits;
2467 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2468 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2470 if ( $cust_main->balance > $old_balance
2471 && $cust_main->balance > 0
2472 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2473 || $status eq 'suspended'
2477 unless ( $opt{'no_credit'} ) {
2478 #this makes sense. credit is "un-doing" the invoice
2479 my $conf = new FS::Conf;
2480 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2481 'self-service decline',
2482 reason_type=>$conf->config('signup_credit_type'),
2484 $cust_main->apply_credits( 'order' => 'newest' );
2487 return { 'error' => '_decline', 'bill_error' => $bill_error };
2496 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2497 return { 'error' => $session } if $context eq 'error';
2499 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2500 or return { 'error' => "unknown custnum $custnum" };
2502 my @cust_pkg = sort { $a->bill <=> $b->bill }
2503 grep { $_->part_pkg->freq ne '0' }
2504 $cust_main->ncancelled_pkgs;
2506 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2508 my $total = $cust_main->balance;
2511 my $bill = $_->bill;
2512 $total += $_->part_pkg->base_recur($_, \$bill);
2513 my $renew_date = $_->part_pkg->add_freq($_->bill);
2515 'pkgnum' => $_->pkgnum,
2516 'amount' => sprintf('%.2f', $total),
2517 'bill_date' => $_->bill,
2518 'bill_date_pretty' => time2str('%x', $_->bill),
2519 'renew_date' => $renew_date,
2520 'renew_date_pretty' => time2str('%x', $renew_date),
2521 'expire_date' => $_->expire,
2522 'expire_date_pretty' => time2str('%x', $_->expire),
2527 return { 'dates' => \@array };
2531 sub payment_info_renew_info {
2533 my $renew_info = renew_info($p);
2534 my $payment_info = payment_info($p);
2535 return { %$renew_info,
2543 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2544 return { 'error' => $session } if $context eq 'error';
2546 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2547 or return { 'error' => "unknown custnum $custnum" };
2549 my $date = $p->{'date'};
2553 #freeside-daily -n -d $date fs_daily $custnum
2554 $cust_main->bill_and_collect( 'time' => $date,
2555 'invoice_time' => $now,
2556 'actual_time' => $now,
2557 'check_freq' => '1d',
2560 return { 'error' => '' };
2566 my $session = _cache->get($p->{'session_id'})
2567 or return { 'error' => "Can't resume session" }; #better error message
2569 my $custnum = $session->{'custnum'};
2571 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2572 or return { 'error' => "unknown custnum $custnum" };
2574 my $conf = new FS::Conf;
2576 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2577 or return { 'error' => 'Permission denied' };
2579 my $pkgnum = $p->{'pkgnum'};
2581 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2582 'pkgnum' => $pkgnum, } )
2583 or return { 'error' => "unknown pkgnum $pkgnum" };
2585 my $error = $cust_pkg->suspend(reason => $reasonnum);
2586 return { 'error' => $error };
2592 my $session = _cache->get($p->{'session_id'})
2593 or return { 'error' => "Can't resume session" }; #better error message
2595 my $custnum = $session->{'custnum'};
2597 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2598 or return { 'error' => "unknown custnum $custnum" };
2600 my $pkgnum = $p->{'pkgnum'};
2602 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2603 'pkgnum' => $pkgnum, } )
2604 or return { 'error' => "unknown pkgnum $pkgnum" };
2606 my $error = $cust_pkg->cancel('quiet' => 1);
2607 return { 'error' => $error };
2611 sub provision_phone {
2614 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2616 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2617 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2618 return { 'error' => $session } if $context eq 'error';
2620 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2621 return { 'error' => 'service not found' } unless $svc_phone;
2622 return { 'error' => 'invalid svcnum' }
2623 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2625 $svc_phone->email($p->{'email'})
2626 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2627 $svc_phone->forwarddst($p->{'forwarddst'})
2628 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2629 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2630 return { 'error' => $svc_phone->replace };
2634 unless($p->{'lnp'}) {
2635 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2636 $p->{'lnp_status'} = "portingin";
2637 return _provision( 'FS::svc_phone',
2638 [qw(lnp_desired_due_date lnp_other_provider
2639 lnp_other_provider_account phonenum countrycode lnp_status)],
2640 [qw(phonenum countrycode)],
2647 unless (scalar(@bulkdid)) {
2648 return _provision( 'FS::svc_phone',
2649 [qw(phonenum countrycode)],
2650 [qw(phonenum countrycode)],
2656 # bulk DID order case
2658 foreach my $did ( @bulkdid ) {
2659 $did =~ s/[^0-9]//g;
2660 $error = _provision( 'FS::svc_phone',
2661 [qw(phonenum countrycode)],
2662 [qw(phonenum countrycode)],
2664 'pkgnum' => $p->{'pkgnum'},
2665 'svcpart' => $p->{'svcpart'},
2667 'countrycode' => $p->{'countrycode'},
2668 'session_id' => $p->{'session_id'},
2671 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2673 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2676 sub provision_acct {
2678 warn "provision_acct called\n"
2681 return { 'error' => gettext('passwords_dont_match') }
2682 if $p->{'_password'} ne $p->{'_password2'};
2683 return { 'error' => gettext('empty_password') }
2684 unless length($p->{'_password'});
2686 if ($p->{'domsvc'}) {
2687 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2688 qw ( svcpart pkgnum ) );
2689 return { 'error' => gettext('invalid_domain') }
2690 unless ($domains{$p->{'domsvc'}});
2693 warn "provision_acct calling _provision\n"
2695 _provision( 'FS::svc_acct',
2696 [qw(username _password domsvc)],
2697 [qw(username _password domsvc)],
2703 sub provision_external {
2705 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2706 _provision( 'FS::svc_external',
2715 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2716 warn "_provision called for $class\n"
2719 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2720 return { 'error' => $session } if $context eq 'error';
2722 my $search = { 'custnum' => $custnum };
2723 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2724 my $cust_main = qsearchs('cust_main', $search )
2725 or return { 'error' => "unknown custnum $custnum" };
2727 my $pkgnum = $p->{'pkgnum'};
2729 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2731 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2732 'pkgnum' => $pkgnum,
2734 or return { 'error' => "unknown pkgnum $pkgnum" };
2736 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2738 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2739 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2741 warn "creating $class record\n"
2743 my $svc_x = $class->new( {
2744 'pkgnum' => $p->{'pkgnum'},
2745 'svcpart' => $p->{'svcpart'},
2746 map { $_ => $p->{$_} } @$fields
2748 warn "inserting $class record\n"
2750 my $error = $svc_x->insert;
2753 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2755 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2758 my $return = { 'svc' => $part_svc->svc,
2760 map { $_ => $svc_x->get($_) } @$return_fields
2762 warn "_provision returning ". Dumper($return). "\n"
2771 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2772 return { 'error' => $session } if $context eq 'error';
2774 my $search = { 'custnum' => $custnum };
2775 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2776 my $cust_main = qsearchs('cust_main', $search )
2777 or return { 'error' => "unknown custnum $custnum" };
2779 my $pkgnum = $p->{'pkgnum'};
2781 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2782 'pkgnum' => $pkgnum,
2784 or return { 'error' => "unknown pkgnum $pkgnum" };
2786 my $svcpart = $p->{'svcpart'};
2788 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2789 'svcpart' => $svcpart, } )
2790 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2791 my $part_svc = $pkg_svc->part_svc;
2793 my $conf = new FS::Conf;
2796 'svc' => $part_svc->svc,
2797 'svcdb' => $part_svc->svcdb,
2798 'pkgnum' => $pkgnum,
2799 'svcpart' => $svcpart,
2800 'custnum' => $custnum,
2802 'security_phrase' => 0, #XXX !
2803 'svc_acct_pop' => [], #XXX !
2805 'init_popstate' => '',
2810 small_custview( $cust_main, $conf->config('countrydefault') ),
2814 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2815 && $ret->{'svcdb'} eq 'svc_phone') {
2816 $ret->{'svcnum'} = $p->{'svcnum'};
2817 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2818 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2819 $ret->{'email'} = $svc_phone->email;
2820 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2827 sub unprovision_svc {
2830 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2831 return { 'error' => $session } if $context eq 'error';
2833 my $search = { 'custnum' => $custnum };
2834 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2835 my $cust_main = qsearchs('cust_main', $search )
2836 or return { 'error' => "unknown custnum $custnum" };
2838 my $svcnum = $p->{'svcnum'};
2840 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2841 or return { 'error' => "unknown svcnum $svcnum" };
2843 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2844 unless $cust_svc->cust_pkg->custnum == $custnum;
2846 my $conf = new FS::Conf;
2848 return { 'svc' => $cust_svc->part_svc->svc,
2849 'error' => $cust_svc->cancel,
2851 small_custview( $cust_main, $conf->config('countrydefault') ),
2856 sub myaccount_passwd {
2858 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2859 return { 'error' => $session } if $context eq 'error';
2861 return { 'error' => "New passwords don't match." }
2862 if $p->{'new_password'} ne $p->{'new_password2'};
2864 return { 'error' => 'Enter new password' }
2865 unless length($p->{'new_password'});
2867 #my $search = { 'custnum' => $custnum };
2868 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2869 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2870 my $search = " AND custnum = $1";
2871 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2873 my $svc_acct = qsearchs( {
2874 'table' => 'svc_acct',
2875 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2876 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2877 'LEFT JOIN cust_main USING ( custnum ) ',
2878 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2879 'extra_sql' => $search, #important
2881 or return { 'error' => "Service not found" };
2885 my $conf = new FS::Conf;
2887 return { 'error' => 'Incorrect current password.' }
2888 if ( exists($p->{'old_password'})
2889 || $conf->exists('selfservice-password_change_oldpass')
2891 && ! $svc_acct->check_password($p->{'old_password'});
2893 $error = 'Password too short.'
2894 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2895 $error = 'Password too long.'
2896 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2898 $svc_acct->set_password($p->{'new_password'});
2899 $error ||= $svc_acct->replace();
2901 #regular pw change in self-service should change contact pw too, otherwise its
2902 #way too confusing. hell its confusing they're separate at all, but alas.
2903 #need to support the "ISP provides email that's used as a contact email" case
2905 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2906 if ( $contact && $contact->custnum == $custnum ) {
2907 #svc_acct was successful but this one returns an error? "shouldn't happen"
2908 $error ||= $contact->change_password($p->{'new_password'});
2911 my($label, $value) = $svc_acct->cust_svc->label;
2913 return { 'error' => $error,
2920 # sub contact_passwd {
2922 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2923 # return { 'error' => $session } if $context eq 'error';
2925 # return { 'error' => 'Not logged in as a contact.' }
2926 # unless $session->{'contactnum'};
2928 # return { 'error' => "New passwords don't match." }
2929 # if $p->{'new_password'} ne $p->{'new_password2'};
2931 # return { 'error' => 'Enter new password' }
2932 # unless length($p->{'new_password'});
2934 # #my $search = { 'custnum' => $custnum };
2935 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2936 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2937 # my $search = " AND selfservice_access IS NOT NULL ".
2938 # " AND selfservice_access = 'Y' ".
2939 # " AND ( disabled IS NULL OR disabled = '' )".
2940 # " AND custnum IS NOT NULL AND custnum = $1";
2941 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2943 # my $contact = qsearchs( {
2944 # 'table' => 'contact',
2945 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2946 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2947 # 'extra_sql' => $search, #important
2949 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2950 # # deleted since then?
2954 # # use these svc_acct length restrictions??
2955 # my $conf = new FS::Conf;
2956 # $error = 'Password too short.'
2957 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2958 # $error = 'Password too long.'
2959 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2961 # $error ||= $contact->change_password($p->{'new_password'});
2963 # return { 'error' => $error, };
2970 my $info = skin_info($p);
2972 my $conf = new FS::Conf;
2973 my $verification = $conf->config('selfservice-password_reset_verification')
2974 or return { %$info, 'error' => 'Password resets disabled' };
2979 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2981 $contact = FS::contact->by_selfservice_email($p->{'email'});
2983 $cust_main = $contact->cust_main if $contact;
2985 #also look for an svc_acct, otherwise it would be super confusing
2987 my($username, $domain) = split('@', $p->{'email'});
2988 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2989 if ( $svc_domain ) {
2990 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2991 'domsvc' => $svc_domain->svcnum }
2994 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2995 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
2997 #precaution: don't change svc_acct password not part of the same
2998 # customer as contact
2999 $svc_acct = '' if ! $cust_pkg
3000 || $cust_pkg->custnum != $cust_main->custnum;
3005 return { %$info, 'error' => 'Email address not found' }
3006 unless $contact || $svc_acct;
3008 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3010 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3011 or return { %$info, 'error' => 'Account not found' };
3013 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3014 'domsvc' => $svc_domain->svcnum }
3016 or return { %$info, 'error' => 'Account not found' };
3018 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3019 or return { %$info, 'error' => 'Account not found' };
3021 $cust_main = $cust_pkg->cust_main;
3026 'email' => sub { 1; },
3028 my( $p, $cust_main ) = @_;
3029 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3030 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3033 my( $p, $cust_main ) = @_;
3034 my $cust_pay = qsearchs({
3035 'table' => 'cust_pay',
3036 'hashref' => { 'custnum' => $cust_main->custnum },
3037 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3041 $p->{'amount'} == $cust_pay->paid;
3044 my( $p, $cust_main ) = @_;
3045 $p->{'zip'} eq $cust_main->zip
3046 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3050 foreach my $verify ( split(',', $verification) ) {
3052 &{ $verify{$verify} }( $p, $cust_main )
3053 or return { %$info, 'error' => 'Account not found' };
3057 #okay, we're verified
3061 my $error = $contact->send_reset_email(
3062 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3066 return { %$info, 'error' => $error }; #????
3069 } elsif ( $svc_acct ) {
3071 #create a unique session
3073 my $reset_session = {
3074 'svcnum' => $svc_acct->svcnum,
3078 my $timeout = '1 hour'; #?
3080 my $reset_session_id;
3082 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3083 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3086 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3090 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3091 $cust_main->agentnum);
3092 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3093 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3095 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3096 my $error = $msg_template->send( 'cust_main' => $cust_main,
3097 'object' => $svc_acct,
3098 'substitutions' => {
3099 'session_id' => $reset_session_id,
3103 return { %$info, 'error' => $error }; #????
3108 return { %$info, 'error' => '' };
3111 sub check_reset_passwd {
3114 my $conf = new FS::Conf;
3115 my $verification = $conf->config('selfservice-password_reset_verification')
3116 or return { 'error' => 'Password resets disabled' };
3118 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3119 or return { 'error' => "Can't resume session" }; #better error message
3121 if ( $reset_session->{'svcnum'} ) {
3123 my $svcnum = $reset_session->{'svcnum'};
3125 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3126 or return { 'error' => "Service not found" };
3128 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3129 my $info = skin_info($p);
3133 'session_id' => $p->{'session_id'},
3134 'username' => $svc_acct->username,
3137 } elsif ( $reset_session->{'contactnum'} ) {
3139 my $contactnum = $reset_session->{'contactnum'};
3141 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3142 or return { 'error' => "Contact not found" };
3144 my @contact_email = $contact->contact_email;
3145 return { 'error' => 'No contact email' } unless @contact_email;
3147 $p->{'agentnum'} = $contact->cust_main->agentnum;
3148 my $info = skin_info($p);
3152 'session_id' => $p->{'session_id'},
3153 'email' => $contact_email[0]->email, #the first?
3158 return { 'error' => 'No svcnum or contactnum in session' }; #??
3164 sub process_reset_passwd {
3167 my $conf = new FS::Conf;
3168 my $verification = $conf->config('selfservice-password_reset_verification')
3169 or return { 'error' => 'Password resets disabled' };
3171 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3172 or return { 'error' => "Can't resume session" }; #better error message
3177 if ( $reset_session->{'svcnum'} ) {
3179 my $svcnum = $reset_session->{'svcnum'};
3181 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3182 or return { 'error' => "Service not found" };
3184 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3185 $info ||= skin_info($p);
3190 if ( $reset_session->{'contactnum'} ) {
3192 my $contactnum = $reset_session->{'contactnum'};
3194 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3195 or return { 'error' => "Contact not found" };
3197 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3198 $info ||= skin_info($p);
3202 return { %$info, 'error' => "New passwords don't match." }
3203 if $p->{'new_password'} ne $p->{'new_password2'};
3205 return { %$info, 'error' => 'Enter new password' }
3206 unless length($p->{'new_password'});
3210 $svc_acct->set_password($p->{'new_password'});
3211 my $error = $svc_acct->replace();
3213 return { %$info, 'error' => $error } if $error;
3215 #my($label, $value) = $svc_acct->cust_svc->label;
3216 #return { 'error' => $error,
3217 # #'label' => $label,
3218 # #'value' => $value,
3225 my $error = $contact->change_password($p->{'new_password'});
3227 return { %$info, 'error' => $error }; # if $error;
3231 #password changed ,so remove session, don't want it reused
3232 _cache->remove($p->{'session_id'});
3234 return { %$info, 'error' => '' };
3240 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3241 return { 'error' => $session } if $context eq 'error';
3244 if ( $session->{'pkgnum'} ) {
3246 #tickets for specific service with pkg-balances on
3247 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3248 'pkgnum' => $session->{'pkgnum'} })
3249 or return { 'error' => 'unknown package' };
3250 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3251 push @tickets, $cust_svc->tickets( $p->{status} );
3256 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3257 or return { 'error' => "unknown custnum $custnum" };
3259 @tickets = $cust_main->tickets( $p->{status} );
3262 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3263 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3264 my $conf = new FS::Conf;
3265 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3269 ($a->{'_selfservice_priority'} eq '') <=>
3270 ($b->{'_selfservice_priority'} eq '')
3273 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3279 +{ tickets => \@tickets };
3286 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3287 return { 'error' => $session } if $context eq 'error';
3289 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3290 FS::TicketSystem->init();
3292 my $conf = new FS::Conf;
3293 my $queue = $p->{'queue'}
3294 || $conf->config('ticket_system-selfservice_queueid')
3295 || $conf->config('ticket_system-default_queueid');
3297 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3298 my $err_or_ticket = FS::TicketSystem->create_ticket(
3299 '', #create RT session based on FS CurrentUser (fs_selfservice)
3301 'custnum' => $custnum,
3302 'svcnum' => $session->{'svcnum'},
3303 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3306 if ( ref($err_or_ticket) ) {
3307 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3309 return { 'error' => '',
3310 'ticket_id' => $err_or_ticket->id,
3313 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3315 return { 'error' => $err_or_ticket };
3323 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3324 return { 'error' => $session } if $context eq 'error';
3326 return { error => 'requested format not implemented' }
3327 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3329 my $conf = new FS::Conf;
3330 my $age_threshold = 0;
3331 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3332 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3334 my $search = { 'custnum' => $custnum };
3335 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3336 my $cust_main = qsearchs('cust_main', $search )
3337 or return { 'error' => "unknown custnum $custnum" };
3339 # does it make more sense to just run one sql query for this instead of all the
3340 # insanity below? would increase performance greately for large data sets?
3342 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3343 my @part_svc = $cust_pkg->part_svc;
3344 foreach my $part_svc ( @part_svc ) {
3345 if($part_svc->svcdb eq 'svc_phone'){
3346 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3347 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3348 push @svc_phone, $cust_pkg_svc->svc_x
3349 if $cust_pkg_svc->date_inserted >= $age_threshold;
3357 my($xls_r,$xls_c) = (0,0);
3360 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3361 if($p->{'format'} eq 'csv') {
3362 $csv = new Text::CSV_XS { 'always_quote' => 1,
3365 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3366 $content .= $csv->string;
3368 elsif($p->{'format'} eq 'xls') {
3369 my $XLS1 = new IO::Scalar \$content;
3370 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3371 or return { 'error' => "Error opening .xls file: $!" };
3372 $xls = $xls_workbook->add_worksheet('DIDs');
3373 foreach ( @fields ) {
3374 $xls->write(0,$xls_c++,$_);
3379 foreach my $svc_phone ( @svc_phone ) {
3380 my @cols = map { $svc_phone->$_ } @fields;
3381 if($p->{'format'} eq 'csv') {
3382 return { 'error' => 'Unable to create CSV' }
3383 unless $csv->combine(@cols);
3384 $content .= $csv->string;
3386 elsif($p->{'format'} eq 'xls') {
3389 $xls->write($xls_r,$xls_c++,$_);
3395 $xls_workbook->close() if $p->{'format'} eq 'xls';
3397 { content => $content, format => $p->{'format'}, };
3402 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3403 return { 'error' => $session } if $context eq 'error';
3405 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3406 # FS::TicketSystem->init();
3407 # return { 'error' => 'get_ticket configuration error' }
3408 # if $FS::TicketSystem::system ne 'RT_Internal';
3410 # check existence and ownership as part of this
3411 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3412 my $rt_session = FS::TicketSystem->session('');
3413 my $Ticket = FS::TicketSystem->get_ticket_object(
3415 ticket_id => $p->{'ticket_id'},
3418 return { 'error' => 'ticket not found' } if !$Ticket;
3420 if ( length( $p->{'subject'} || '' ) ) {
3422 if ( $p->{'subject'} ne $Ticket->Subject ) {
3423 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3424 return { 'error' => "unable to set subject: $msg" } if !$val;
3428 if(length($p->{'reply'})) {
3429 my @err_or_res = FS::TicketSystem->correspond_ticket(
3431 'ticket_id' => $p->{'ticket_id'},
3432 'content' => $p->{'reply'},
3435 return { 'error' => 'unable to reply to ticket' }
3436 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3439 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3440 my $err_or_ticket = FS::TicketSystem->get_ticket(
3442 'ticket_id' => $p->{'ticket_id'},
3445 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3446 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3448 return { 'error' => $err_or_ticket };
3451 my @custs = @{$err_or_ticket->{'custs'}};
3452 my @txns = @{$err_or_ticket->{'txns'}};
3455 # superseded by check in get_ticket_object
3456 #return { 'error' => 'invalid ticket requested' }
3457 #unless grep($_ eq $custnum, @custs);
3459 foreach my $txn ( @txns ) {
3460 push @filtered_txns, $txn
3461 if ($txn->{'type'} eq 'EmailRecord'
3462 || $txn->{'type'} eq 'Correspond'
3463 || $txn->{'type'} eq 'Create');
3466 warn "$me get_ticket: successful: \n"
3468 return { 'error' => '',
3469 'transactions' => \@filtered_txns,
3470 'ticket_fields' => $err_or_ticket->{'fields'},
3471 'ticket_id' => $p->{'ticket_id'},
3475 sub adjust_ticket_priority {
3477 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3478 return { 'error' => $session } if $context eq 'error';
3480 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3481 # FS::TicketSystem->init;
3482 my $ss_priority = FS::TicketSystem->selfservice_priority;
3484 return { 'error' => 'adjust_ticket_priority configuration error' }
3485 if $FS::TicketSystem::system ne 'RT_Internal'
3488 my $values = $p->{'values'}; #hashref, id => priority value
3491 foreach my $id (keys %$values) {
3492 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3493 my $Ticket = FS::TicketSystem->get_ticket_object('',
3495 'custnum' => $custnum,
3498 $ticket_error{$id} = 'ticket not found';
3502 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3503 # We're not going to implement it for RT_External.
3504 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3505 my $new_value = $values->{$id};
3506 next if $old_value eq $new_value;
3508 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3510 # AddCustomFieldValue works fine (replacing any existing value) if it's
3511 # a single-valued custom field, which it should be. If it's not, you're
3512 # doing something wrong.
3514 if ( length($new_value) ) {
3515 ($val, $msg) = $Ticket->AddCustomFieldValue(
3516 Field => $ss_priority,
3517 Value => $new_value,
3521 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3522 Field => $ss_priority,
3523 Value => $old_value,
3527 $ticket_error{$id} = $msg if !$val;
3528 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3530 return { 'error' => '',
3531 'ticket_error' => \%ticket_error,
3532 %{ customer_info($p) } # send updated customer info back
3538 sub _custoragent_session_custnum {
3541 my($context, $session, $custnum);
3542 if ( $p->{'session_id'} ) {
3544 $context = 'customer';
3545 $session = _cache->get($p->{'session_id'})
3546 or return ( 'error' => "Can't resume session" ); #better error message
3547 $custnum = $session->{'custnum'};
3549 } elsif ( $p->{'agent_session_id'} ) {
3552 my $agent_cache = new FS::ClientAPI_SessionCache( {
3553 'namespace' => 'FS::ClientAPI::Agent',
3555 $session = $agent_cache->get($p->{'agent_session_id'})
3556 or return ( 'error' => "Can't resume session" ); #better error message
3557 $custnum = $p->{'custnum'};
3561 return ( 'error' => "Can't resume session" ); #better error message
3564 ($context, $session, $custnum);