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 money_pretty);
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;
50 use FS::cust_location;
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
58 $me = '[FS::ClientAPI::MyAccount]';
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62 first last company daytime night fax mobile
64 ss stateid stateid_state
66 @location_editable_fields = qw(
67 address1 address2 city county state zip country
71 BEGIN { #preload to reduce time customer_info takes
72 if ( $FS::TicketSystem::system ) {
73 warn "$me: initializing ticket system\n" if $DEBUG;
74 FS::TicketSystem->init();
79 $cache ||= new FS::ClientAPI_SessionCache( {
80 'namespace' => 'FS::ClientAPI::MyAccount',
87 my($context, $session, $custnum) = _custoragent_session_custnum($p);
88 #return { 'error' => $session } if $context eq 'error';
91 if ( $context eq 'customer' && $custnum ) {
93 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
96 $sth->execute($custnum) or die $sth->errstr;
98 $agentnum = $sth->fetchrow_arrayref->[0]
99 or die "no agentnum for custnum $custnum";
101 #} elsif ( $context eq 'agent' ) {
102 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
105 $p->{'agentnum'} = $agentnum;
107 my $conf = new FS::Conf;
109 #false laziness w/Signup.pm
111 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
113 if ( $skin_info_cache_agent ) {
115 warn "$me loading cached skin info for agentnum $agentnum\n"
120 warn "$me populating skin info cache for agentnum $agentnum\n"
123 $skin_info_cache_agent = {
124 'agentnum' => $agentnum,
125 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
126 qw( company_name date_format ) ),
127 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
128 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
129 text_color link_color vlink_color hlink_color alink_color
130 font title_color title_align title_size menu_bgcolor menu_fontsize
133 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
134 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
135 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
137 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
138 qw( title_left_image title_right_image
139 menu_top_image menu_body_image menu_bottom_image
142 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
143 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
144 qw( head body_header body_footer company_address ) ),
145 'money_char' => $conf->config("money_char") || '$',
146 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
149 services.php Services
150 services.php My Services
151 services_new.php Order a new service
154 personal.php Personal Information
155 password.php Change Password
158 payment_cc.php Credit Card Payment
159 payment_ach.php Electronic Check Payment
160 payment_paypal.php PayPal Payment
161 payment_webpay.php Webpay Payments
164 usage_data.php Data usage
165 usage_cdr.php Call usage
167 tickets.php Help Desk
168 tickets.php Open Tickets
169 tickets_resolved.php Resolved Tickets
170 ticket_create.php Create a new ticket
178 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
182 #{ %$skin_info_cache_agent };
183 $skin_info_cache_agent;
190 my $conf = new FS::Conf;
194 'phone_login' => $conf->exists('selfservice_server-phone_login'),
195 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
196 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
197 'banner_image_md5' =>
198 md5_hex($conf->config_binary('selfservice-login_banner_image')),
205 sub login_banner_image {
207 my $conf = new FS::Conf;
208 my $image = $conf->config_binary('selfservice-login_banner_image');
210 'md5' => md5_hex($image),
215 #false laziness w/FS::ClientAPI::passwd::passwd
219 my $conf = new FS::Conf;
223 if ( $p->{'domain'} eq 'svc_phone'
224 && $conf->exists('selfservice_server-phone_login') ) {
226 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
227 return { error => 'Number not found.' } unless $svc_phone;
230 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
231 #return { error => 'Only primary user may log in.' }
232 # if $conf->exists('selfservice_server-primary_only')
233 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
235 return { error => 'Incorrect PIN.' }
236 unless $svc_phone->check_pin($p->{'password'});
240 } elsif ( $p->{email}
241 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
244 return { error => 'Incorrect contact password.' }
245 unless $contact->authenticate_password($p->{'password'});
247 $session->{'contactnum'} = $contact->contactnum;
249 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
250 if ( scalar(@cust_contact) == 1 ) {
251 $session->{'custnum'} = $cust_contact[0]->custnum;
252 } elsif ( scalar(@cust_contact) ) {
253 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
257 return { error => 'No customer self-service access for contact' }; #??
262 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
264 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
265 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
267 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
268 'domsvc' => $svc_domain->svcnum, }
271 if ( $conf->exists('selfservice_server-login_svcpart') ) {
272 my @svcpart = $conf->config('selfservice_server-login_svcpart');
273 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
274 scalar( grep( $_ eq $svcpart, @svcpart ) );
279 if ( $conf->exists('selfservice_server-primary_only') ) {
282 my $cust_svc = $_->cust_svc;
283 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
284 == $cust_svc->svcpart
289 return { error => 'User not found.' } unless @svc_acct;
291 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
293 my $svc_acct = $svc_acct[0];
295 if ( $conf->exists('selfservice_server-login_svcpart') ) {
296 my @svcpart = $conf->config('selfservice_server-login_svcpart');
297 my $svcpart = $svc_acct->cust_svc->svcpart;
298 return { error => 'Invalid user.' }
299 unless grep($_ eq $svcpart, @svcpart);
302 return { error => 'Incorrect password.' }
303 unless $svc_acct->check_password($p->{'password'});
311 $session->{'svcnum'} = $svc_x->svcnum;
313 my $cust_svc = $svc_x->cust_svc;
314 my $cust_pkg = $cust_svc->cust_pkg;
316 my $cust_main = $cust_pkg->cust_main;
317 $session->{'custnum'} = $cust_main->custnum;
318 if ( $conf->exists('pkg-balances') ) {
319 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
320 $cust_main->ncancelled_pkgs;
321 $session->{'pkgnum'} = $cust_pkg->pkgnum
322 if scalar(@cust_pkg) > 1;
326 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
327 #return { error => 'Only primary user may log in.' }
328 # if $conf->exists('selfservice_server-primary_only')
329 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
330 my $part_pkg = $cust_pkg->part_pkg;
331 return { error => 'Only primary user may log in.' }
332 if $conf->exists('selfservice_server-primary_only')
333 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
339 $session_id = sha512_hex(time(). {}. rand(). $$)
340 } until ( ! defined _cache->get($session_id) ); #just in case
342 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
343 _cache->set( $session_id, $session, $timeout );
345 return { 'error' => '',
346 'session_id' => $session_id,
353 my $skin_info = skin_info($p);
354 if ( $p->{'session_id'} ) {
355 _cache->remove($p->{'session_id'});
356 return { %$skin_info, 'error' => '' };
358 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
365 my($context, $session, $custnum) = _custoragent_session_custnum($p);
366 return { 'error' => $session } if $context eq 'error';
368 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
369 or return { 'error' => "Service not found" };
371 $session->{'svcnum'} = $svc_acct->svcnum;
373 my $conf = new FS::Conf;
374 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
375 _cache->set( $p->{'session_id'}, $session, $timeout );
377 return { 'error' => '' };
383 my($context, $session, $custnum) = _custoragent_session_custnum($p);
384 return { 'error' => $session } if $context eq 'error';
386 $session->{'custnum'} = $p->{'custnum'}
387 if exists $session->{'customers'}{ $p->{'custnum'} };
389 my $conf = new FS::Conf;
390 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
391 _cache->set( $p->{'session_id'}, $session, $timeout );
393 return { 'error' => '',
394 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
398 sub payment_gateway {
400 # takes a cust_main and a cust_payby entry, returns the payment_gateway
401 my $conf = new FS::Conf;
402 my $cust_main = shift;
403 my $cust_payby = shift;
404 my $gatewaynum = $conf->config('selfservice-payment_gateway');
406 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
407 die "configured gatewaynum $gatewaynum not found!" if !$pg;
411 return '' if ! FS::payby->realtime($cust_payby);
412 my $pg = $cust_main->agent->payment_gateway(
413 'method' => FS::payby->payby2bop($cust_payby),
423 my $conf = new FS::Conf;
425 my $info = skin_info($p);
427 use vars qw( $cust_paybys ); #cache for performance
428 unless ( $cust_paybys ) {
430 my %cust_paybys = map { $_ => 1 }
431 map { FS::payby->payby2payment($_) }
432 $conf->config('signup_server-payby');
434 $cust_paybys = [ keys %cust_paybys ];
437 $info->{'cust_paybys'} = $cust_paybys;
439 my($context, $session, $custnum) = _custoragent_session_custnum($p);
440 return { 'error' => $session } if $context eq 'error';
442 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
444 $info->{'hide_payment_fields'} = [
446 my $pg = $cust_main && payment_gateway($cust_main, $_);
447 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
448 } @{ $info->{cust_paybys} }
451 $info->{'self_suspend_reason'} =
452 $conf->config('selfservice-self_suspend_reason',
453 $cust_main ? $cust_main->agentnum : ''
456 $info->{'edit_ticket_subject'} =
457 $conf->exists('ticket_system-selfservice_edit_subject') &&
458 $cust_main && $cust_main->edit_subject;
460 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
462 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
465 'custnum' => $custnum,
466 'access_pkgnum' => $session->{'pkgnum'},
467 'access_svcnum' => $session->{'svcnum'},
474 my($context, $session, $custnum) = _custoragent_session_custnum($p);
475 return { 'error' => $session } if $context eq 'error';
479 my $conf = new FS::Conf;
480 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
482 # if ( $FS::TicketSystem::system ) {
483 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
484 # FS::TicketSystem->init();
487 if ( $custnum ) { #customer record
489 %return = ( %return, %{ customer_info_short($p) } );
491 #redundant with customer_info_short, but we need it for several things below
492 my $search = { 'custnum' => $custnum };
493 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
494 my $cust_main = qsearchs('cust_main', $search )
495 or return { 'error' => "customer_info: unknown custnum $custnum" };
497 my $list_tickets = list_tickets($p);
498 $return{'tickets'} = $list_tickets->{'tickets'};
500 if ( $session->{'pkgnum'} ) {
501 #XXX open invoices in the pkg-balances case
503 $return{'money_char'} = $conf->config("money_char") || '$';
506 invnum => $_->invnum,
507 date => time2str("%b %o, %Y", $_->_date),
509 charged => $_->charged,
511 } $cust_main->open_cust_bill;
512 $return{open_invoices} = \@open;
514 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
515 my $sth = dbh->prepare($sql) or die dbh->errstr;
516 $sth->execute($custnum) or die $sth->errstr;
517 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
518 $return{'last_invoice_date_pretty'} =
519 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
522 #customer_info_short always has nobalance on..
523 $return{small_custview} =
524 small_custview( $cust_main,
525 $return{countrydefault},
526 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
529 $return{has_ship_address} = $cust_main->has_ship_address;
530 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
531 $return{statuscolor} = $cust_main->statuscolor;
532 $return{status_label} = $cust_main->status_label;
534 # compatibility: some places in selfservice use this to determine
535 # if there's a ship address
536 if ( $return{has_ship_address} ) {
537 $return{ship_last} = $cust_main->last;
538 $return{ship_first} = $cust_main->first;
541 if (scalar($conf->config('support_packages'))) {
542 my @support_services = ();
543 foreach ($cust_main->support_services) {
544 my $seconds = $_->svc_x->seconds || 0;
545 my $time_remaining = (($seconds < 0) ? '-' : '' ).
546 int(abs($seconds)/3600)."h".
547 sprintf("%02d",(abs($seconds)%3600)/60)."m";
548 my $cust_pkg = $_->cust_pkg;
551 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
552 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
553 push @support_services, { svcnum => $_->svcnum,
554 time => $time_remaining,
559 $return{support_services} = \@support_services;
562 if ( $conf->config('prepayment_discounts-credit_type') ) {
564 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
567 } elsif ( $session->{'svcnum'} ) { #no customer record
569 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
570 or die "unknown svcnum";
571 $return{name} = $svc_acct->email;
575 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
579 return { 'error' => '',
580 'custnum' => $custnum,
586 sub customer_info_short {
589 my($context, $session, $custnum) = _custoragent_session_custnum($p);
590 return { 'error' => $session } if $context eq 'error';
594 my $conf = new FS::Conf;
596 if ( $custnum ) { #customer record
598 my $search = { 'custnum' => $custnum };
599 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
600 my $cust_main = qsearchs('cust_main', $search )
601 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
603 $return{display_custnum} = $cust_main->display_custnum;
605 if ( $session->{'pkgnum'} ) {
606 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
607 #next_bill_date from cust_pkg?
609 $return{balance} = $cust_main->balance;
610 $return{next_bill_date} = $cust_main->next_bill_date;
611 $return{next_bill_date_pretty} =
612 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
615 $return{balance_pretty} = money_pretty($return{balance});
617 $return{countrydefault} = scalar($conf->config('countrydefault'));
619 $return{small_custview} =
620 small_custview( $cust_main,
621 $return{countrydefault},
625 $return{first} = $cust_main->first;
626 $return{'last'} = $cust_main->get('last');
627 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
629 #none of these are terribly expensive if we want 'em...
630 for (@cust_main_editable_fields) {
631 $return{$_} = $cust_main->get($_);
633 #maybe a little more expensive, but it should be cached by now
634 for (@location_editable_fields) {
635 $return{$_} = $cust_main->bill_location->get($_)
636 if $cust_main->bill_locationnum;
637 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
638 if $cust_main->ship_locationnum;
641 my @invoicing_list = $cust_main->invoicing_list;
642 $return{'invoicing_list'} =
643 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
644 $return{'postal_invoicing'} =
645 0 < ( grep { $_ eq 'POST' } @invoicing_list );
647 if ( $session->{'svcnum'} ) {
648 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
649 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
650 $return{'svcnum'} = $session->{'svcnum'};
653 } elsif ( $session->{'svcnum'} ) { #no customer record
655 #uuh, not supproted yet... die?
656 return { 'error' => 'customer_info_short not yet supported as agent' };
660 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
664 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
665 # it is not customer-specific, though it is only shown to authenticated customers
666 # it is not currently agent-specific, though at some point it might be
667 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
669 return { 'error' => '',
670 'custnum' => $custnum,
675 sub billing_history {
678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
679 return { 'error' => $session } if $context eq 'error';
681 return { 'error' => 'No customer' } unless $custnum;
683 my $search = { 'custnum' => $custnum };
684 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
685 my $cust_main = qsearchs('cust_main', $search )
686 or return { 'error' => "unknown custnum $custnum" };
690 if ( $session->{'pkgnum'} ) {
691 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
692 #next_bill_date from cust_pkg?
693 return { 'error' => 'No history for package' };
696 $return{balance} = $cust_main->balance;
697 $return{balance_pretty} = money_pretty($return{balance});
698 $return{next_bill_date} = $cust_main->next_bill_date;
699 $return{next_bill_date_pretty} =
700 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
703 my $conf = new FS::Conf;
705 $return{'history'} = [
706 $cust_main->payment_history(
707 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
712 $return{'money_char'} = $conf->config("money_char") || '$',
720 my $session = _cache->get($p->{'session_id'})
721 or return { 'error' => "Can't resume session" }; #better error message
723 my $custnum = $session->{'custnum'}
724 or return { 'error' => "no customer record" };
726 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
727 or return { 'error' => "unknown custnum $custnum" };
729 my $new = new FS::cust_main { $cust_main->hash };
731 $new->set( $_ => $p->{$_} )
732 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
734 if ( exists($p->{address1}) ) {
735 my $bill_location = FS::cust_location->new({
736 map { $_ => $p->{$_} } @location_editable_fields
738 # if this is unchanged from before, cust_main::replace will ignore it
739 $new->set('bill_location' => $bill_location);
742 if ( exists($p->{ship_address1}) ) {
743 my $ship_location = FS::cust_location->new({
744 map { $_ => $p->{"ship_$_"} } @location_editable_fields
746 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
747 # Selfservice unfortunately tries to indicate "same as billing
748 # address" by sending all fields empty. Did this ever work?
749 $ship_location = $cust_main->bill_location;
751 $new->set('ship_location' => $ship_location);
753 # but if it hasn't been passed in at all, leave ship_location alone--
754 # DON'T change it to match bill_location.
756 my $conf = new FS::Conf;
759 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
760 #false laziness with httemplate/edit/process/cust_main.cgi
761 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
762 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
764 @invoicing_list = $cust_main->invoicing_list;
767 my $error = $new->replace($cust_main, \@invoicing_list);
768 return { 'error' => $error } if $error;
771 return { 'error' => '' };
776 my $session = _cache->get($p->{'session_id'})
777 or return { 'error' => "Can't resume session" }; #better error message
783 my $conf = new FS::Conf;
784 use vars qw($payment_info); #cache for performance
785 unless ( $payment_info ) {
787 my %states = map { $_->state => 1 }
788 qsearch('cust_main_county', {
789 'country' => $conf->config('countrydefault') || 'US'
792 my %cust_paybys = map { $_ => 1 }
793 map { FS::payby->payby2payment($_) }
794 $conf->config('signup_server-payby');
796 my @cust_paybys = keys %cust_paybys;
800 #list all counties/states/countries
801 'cust_main_county' =>
802 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
804 #shortcut for one-country folks
806 [ sort { $a cmp $b } keys %states ],
808 'card_types' => card_types(),
810 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
811 'require_cvv' => $conf->exists('selfservice-require_cvv'),
812 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
814 'paytypes' => [ FS::cust_payby::paytypes ],
816 'paybys' => [ $conf->config('signup_server-payby') ],
817 'cust_paybys' => \@cust_paybys,
819 'stateid_label' => FS::Msgcat::_gettext('stateid'),
820 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
822 'show_ss' => $conf->exists('show_ss'),
823 'show_stateid' => $conf->exists('show_stateid'),
824 'show_paystate' => $conf->exists('show_bankstate'),
826 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
828 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
837 my %return = %$payment_info;
839 my $custnum = $session->{'custnum'};
841 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
842 or return { 'error' => "unknown custnum $custnum" };
844 $return{'hide_payment_fields'} = [
846 my $pg = payment_gateway($cust_main, $_);
847 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
848 } @{ $return{cust_paybys} }
851 $return{balance} = $cust_main->balance; #XXX pkg-balances?
853 $return{$_} = $cust_main->bill_location->get($_)
854 for qw(address1 address2 city state zip);
856 #XXX look for stored cust_payby info
858 # $return{payname} = $cust_main->payname
859 # || ( $cust_main->first. ' '. $cust_main->get('last') );
861 #if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
862 # $return{card_type} = cardtype($cust_main->payinfo);
863 # $return{payinfo} = $cust_main->paymask;
865 # @return{'month', 'year'} = $cust_main->paydate_monthyear;
869 #if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
870 # my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
871 # $return{payinfo1} = $payinfo1;
872 # $return{payinfo2} = $payinfo2;
873 # $return{paytype} = $cust_main->paytype;
874 # $return{paystate} = $cust_main->paystate;
875 # $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
878 if ( $conf->config('prepayment_discounts-credit_type') ) {
880 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
883 #doubleclick protection
885 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
886 $return{paybatch} = $return{payunique}; #back compat
888 return { 'error' => '',
894 #some false laziness with httemplate/process/payment.cgi - look there for
895 #ACH and CVV support stuff
897 sub validate_payment {
900 my $session = _cache->get($p->{'session_id'})
901 or return { 'error' => "Can't resume session" }; #better error message
903 my $custnum = $session->{'custnum'};
905 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
906 or return { 'error' => "unknown custnum $custnum" };
908 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
909 or return { 'error' => gettext('illegal_amount') };
911 return { error => 'Amount must be greater than 0' } unless $amount > 0;
913 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
914 #changing the hidden form values
915 my $conf = new FS::Conf;
916 my $fee_display = $conf->config('selfservice_process-display') || 'add';
917 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
918 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
919 if ( $fee_display eq 'add'
921 and ! $fee_skip_first || scalar($cust_main->cust_pay)
924 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
925 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
928 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
929 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
930 my $discount_term = $1;
932 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
933 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
936 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
937 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
940 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
941 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
944 $payunique = $paybatch if ! length($payunique) && length($paybatch);
946 $p->{'payby'} ||= 'CARD';
947 $p->{'payby'} =~ /^([A-Z]{4})$/
948 or return { 'error' => "illegal_payby " . $p->{'payby'} };
951 #false laziness w/process/payment.cgi
954 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
956 $p->{'payinfo1'} =~ /^([\dx]+)$/
957 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
959 $p->{'payinfo2'} =~ /^([\dx]+)$/
960 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
962 $payinfo = $payinfo1. '@'. $payinfo2;
964 $payinfo = $cust_main->payinfo
965 if $cust_main->paymask eq $payinfo;
967 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
969 $payinfo = $p->{'payinfo'};
973 #more intelligent matching will be needed here if you change
974 #card_masking_method and don't remove existing paymasks
975 if ( $cust_main->paymask eq $payinfo ) {
976 $payinfo = $cust_main->payinfo;
981 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
982 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
986 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
987 return { 'error' => gettext('unknown_card_type') }
988 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
990 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
991 if ( cardtype($payinfo) eq 'American Express card' ) {
992 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
993 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
996 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
997 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1000 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1001 return { 'error' => 'CVV2 is required' };
1002 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1003 return { 'error' => 'CVV2 is required' };
1007 die "unknown payby $payby";
1010 my %payby2fields = (
1011 'CARD' => [ qw( paystart_month paystart_year payissue payip
1012 address1 address2 city state zip country ) ],
1013 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1017 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1020 'cust_main' => $cust_main, #XXX or just custnum??
1021 'amount' => sprintf('%.2f', $amount),
1023 'payinfo' => $payinfo,
1024 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1025 'card_type' => $card_type,
1026 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1027 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1028 'month' => $p->{'month'},
1029 'year' => $p->{'year'},
1030 'payname' => $payname,
1031 'payunique' => $payunique,
1032 'paybatch' => $paybatch,
1033 'paycvv' => $paycvv,
1034 'payname' => $payname,
1035 'discount_term' => $discount_term,
1036 'pkgnum' => $session->{'pkgnum'},
1037 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1047 my $validate = validate_payment($p);
1048 return $validate if $validate->{'error'};
1050 my $conf = new FS::Conf;
1051 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1052 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1054 +{ map { $_=>$validate->{$_} }
1055 qw( card_type paymask payname paydate_pretty month year amount
1056 address1 address2 city state zip country
1062 sub process_stored_payment {
1065 my $session_id = $p->{'session_id'};
1067 my $payment_info = _cache->get( "payment_$session_id" )
1068 or return { 'error' => "Can't resume session" }; #better error message
1070 do_process_payment($payment_info);
1074 sub process_payment {
1077 my $payment_info = validate_payment($p);
1078 return $payment_info if $payment_info->{'error'};
1080 do_process_payment($payment_info);
1084 sub do_process_payment {
1085 my $validate = shift;
1087 my $cust_main = $validate->{'cust_main'};
1089 my $amount = delete $validate->{'amount'};
1092 my $payby = delete $validate->{'payby'};
1094 if ( $validate->{'save'} ) {
1095 my $new = new FS::cust_main { $cust_main->hash };
1096 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1097 $new->set( $_ => $validate->{$_} )
1098 foreach qw( payname paystart_month paystart_year payissue payip );
1099 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1101 my $bill_location = FS::cust_location->new({
1102 map { $_ => $validate->{$_} }
1103 qw(address1 address2 city state country zip)
1105 $new->set('bill_location' => $bill_location);
1106 # but don't allow the service address to change this way.
1108 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1109 $new->set( $_ => $validate->{$_} )
1110 foreach qw( payname payip paytype paystate
1111 stateid stateid_state );
1112 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1114 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1115 $new->set( 'paydate' => $validate->{'paydate'} );
1116 my $error = $new->replace($cust_main);
1118 #no, this causes customers to process their payments again
1119 #return { 'error' => $error };
1120 #XXX just warn verosely for now so i can figure out how these happen in
1121 # the first place, eventually should redirect them to the "change
1122 #address" page but indicate if the payment processed?
1123 delete($validate->{'payinfo'}); #don't want to log this!
1124 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1125 "NEW: ". Dumper($new)."\n".
1126 "OLD: ". Dumper($cust_main)."\n".
1127 "PACKET: ". Dumper($validate)."\n";
1133 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1137 'paynum_ref' => \$paynum,
1140 return { 'error' => $error } if $error;
1142 #no error, so order the fee package if applicable...
1143 my $conf = new FS::Conf;
1144 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1145 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1147 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1149 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1151 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1152 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1155 #and generate an invoice for it now too
1156 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1157 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1162 $cust_main->apply_payments;
1165 my $receipt_html = '';
1167 # currently supported for realtime CC only; send receipt data to SS
1168 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1171 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1174 <TD ALIGN="right">Payment#</TD>
1175 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1179 <TD ALIGN="right">Date</TD>
1181 <TD BGCOLOR="#FFFFFF"><B>! .
1182 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1188 <TD ALIGN="right">Amount</TD>
1189 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1194 <TD ALIGN="right">Payment method</TD>
1195 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1208 'amount' => sprintf('%.2f', $cust_pay->paid),
1209 'date' => $cust_pay->_date,
1210 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1211 'time_pretty' => time2str('%T', $cust_pay->_date),
1212 'auth_num' => $cust_pay->auth,
1213 'order_num' => $cust_pay->order_number,
1214 'receipt_html' => $receipt_html,
1221 'receipt_html' => '',
1228 sub realtime_collect {
1231 my $session = _cache->get($p->{'session_id'})
1232 or return { 'error' => "Can't resume session" }; #better error message
1234 my $custnum = $session->{'custnum'};
1236 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1237 or return { 'error' => "unknown custnum $custnum" };
1240 if ( $p->{'amount'} ) {
1241 $amount = $p->{'amount'};
1243 elsif ( $session->{'pkgnum'} ) {
1244 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1247 $amount = $cust_main->balance;
1250 my $error = $cust_main->realtime_collect(
1251 'method' => $p->{'method'},
1252 'amount' => $amount,
1253 'pkgnum' => $session->{'pkgnum'},
1254 'session_id' => $p->{'session_id'},
1258 return { 'error' => $error } unless ref( $error );
1260 return { 'error' => '', amount => $amount, %$error };
1263 sub start_thirdparty {
1265 my $session = _cache->get($p->{'session_id'})
1266 or return { 'error' => "Can't resume session" }; #better error message
1267 my $custnum = $session->{'custnum'};
1268 my $cust_main = FS::cust_main->by_key($custnum);
1270 my $amount = $p->{'amount'}
1271 or return { error => 'no amount' };
1273 my $result = $cust_main->create_payment(
1274 'method' => $p->{'method'},
1275 'amount' => $p->{'amount'},
1276 'pkgnum' => $session->{'pkgnum'},
1277 'session_id' => $p->{'session_id'},
1280 if ( ref($result) ) { # hashref or error
1283 return { error => $result };
1287 sub finish_thirdparty {
1289 my $session_id = delete $p->{'session_id'};
1290 my $session = _cache->get($session_id)
1291 or return { 'error' => "Can't resume session" };
1292 my $custnum = $session->{'custnum'};
1293 my $cust_main = FS::cust_main->by_key($custnum);
1295 if ( $p->{_cancel} ) {
1296 # customer backed out of making a payment
1297 return $cust_main->cancel_payment( $session_id );
1299 my $result = $cust_main->execute_payment( $session_id, %$p );
1300 if ( ref($result) ) {
1303 return { error => $result };
1307 sub process_payment_order_pkg {
1310 my $hr = process_payment($p);
1311 return $hr if $hr->{'error'};
1316 sub process_payment_order_renew {
1319 my $hr = process_payment($p);
1320 return $hr if $hr->{'error'};
1325 sub process_prepay {
1329 my $session = _cache->get($p->{'session_id'})
1330 or return { 'error' => "Can't resume session" }; #better error message
1334 my $custnum = $session->{'custnum'};
1336 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1337 or return { 'error' => "unknown custnum $custnum" };
1339 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1340 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1348 return { 'error' => $error } if $error;
1350 return { 'error' => '',
1351 'amount' => $amount,
1352 'seconds' => $seconds,
1353 'duration' => duration_exact($seconds),
1354 'upbytes' => $upbytes,
1355 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1356 'downbytes' => $downbytes,
1357 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1358 'totalbytes'=> $totalbytes,
1359 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1366 my $session = _cache->get($p->{'session_id'})
1367 or return { 'error' => "Can't resume session" }; #better error message
1369 my $custnum = $session->{'custnum'};
1371 my $invnum = $p->{'invnum'};
1373 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1374 'custnum' => $custnum } )
1375 or return { 'error' => "Can't find invnum" };
1379 return { 'error' => '',
1380 'invnum' => $invnum,
1381 'invoice_text' => join('', $cust_bill->print_text ),
1382 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1389 my $session = _cache->get($p->{'session_id'})
1390 or return { 'error' => "Can't resume session" }; #better error message
1392 my $custnum = $session->{'custnum'};
1394 my $invnum = $p->{'invnum'};
1396 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1397 'custnum' => $custnum } )
1398 or return { 'error' => "Can't find invnum" };
1402 return { 'error' => '',
1403 'invnum' => $invnum,
1404 'invoice_pdf' => $cust_bill->print_pdf({
1405 'unsquelch_cdr' => 1,
1406 'locale' => $p->{'locale'},
1412 sub legacy_invoice {
1414 my $session = _cache->get($p->{'session_id'})
1415 or return { 'error' => "Can't resume session" }; #better error message
1417 my $custnum = $session->{'custnum'};
1419 my $legacyinvnum = $p->{'legacyinvnum'};
1422 'legacyinvnum' => $legacyinvnum,
1423 'custnum' => $custnum,
1426 my $legacy_cust_bill =
1427 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1428 || qsearchs('legacy_cust_bill', \%hash )
1429 or return { 'error' => "Can't find legacyinvnum" };
1433 return { 'error' => '',
1434 'legacyinvnum' => $legacyinvnum,
1435 'legacyid' => $legacy_cust_bill->legacyid,
1436 'invoice_html' => $legacy_cust_bill->content_html,
1441 sub legacy_invoice_pdf {
1443 my $session = _cache->get($p->{'session_id'})
1444 or return { 'error' => "Can't resume session" }; #better error message
1446 my $custnum = $session->{'custnum'};
1448 my $legacyinvnum = $p->{'legacyinvnum'};
1450 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1451 'legacyinvnum' => $legacyinvnum,
1452 'custnum' => $custnum,
1453 }) or return { 'error' => "Can't find legacyinvnum" };
1457 return { 'error' => '',
1458 'legacyinvnum' => $legacyinvnum,
1459 'legacyid' => $legacy_cust_bill->legacyid,
1460 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1468 #sessioning for this? how do we get the session id to the backend invoice
1469 # template so it can add it to the link, blah
1472 if ( $p->{'invnum'} ) {
1473 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1474 or return { 'error' => 'unknown invnum' };
1475 $agentnum = $cust_bill->cust_main->agentnum;
1478 my $templatename = $p->{'template'} || $p->{'templatename'};
1480 #false laziness-ish w/view/cust_bill-logo.cgi
1482 my $conf = new FS::Conf;
1483 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1484 $templatename = "_$1";
1489 my $filename = "logo$templatename.png";
1491 return { 'error' => '',
1492 'logo' => $conf->config_binary($filename, $agentnum),
1493 'content_type' => 'image/png', #should allow gif, jpg too
1499 my $session = _cache->get($p->{'session_id'})
1500 or return { 'error' => "Can't resume session" }; #better error message
1502 my $custnum = $session->{'custnum'};
1504 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1505 or return { 'error' => "unknown custnum $custnum" };
1507 my $conf = new FS::Conf;
1509 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1511 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1516 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1517 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1518 my $owed = $_->owed;
1520 +{ 'invnum' => $_->invnum,
1521 '_date' => $_->_date,
1522 'date' => time2str("%b %o, %Y", $_->_date),
1523 'date_short' => time2str("%m-%d-%Y", $_->_date),
1524 'previous' => sprintf('%.2f', ($_->previous)[0]),
1525 'charged' => sprintf('%.2f', $_->charged),
1526 'owed' => sprintf('%.2f', $owed),
1527 'balance' => sprintf('%.2f', $balance),
1528 'lastpay' => @payments_and_credits
1529 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1535 return { 'error' => '',
1536 'balance' => $cust_main->balance,
1537 'money_char' => $conf->config("money_char") || '$',
1538 'invoices' => $invoices,
1539 'legacy_invoices' => [
1541 +{ 'legacyinvnum' => $_->legacyinvnum,
1542 'legacyid' => $_->legacyid,
1543 '_date' => $_->_date,
1544 'date' => time2str("%b %o, %Y", $_->_date),
1545 'date_short' => time2str("%m-%d-%Y", $_->_date),
1546 'charged' => sprintf('%.2f', $_->charged),
1547 'has_content' => ( length($_->content_pdf)
1548 || length($_->content_html) ),
1559 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1560 return { 'error' => $session } if $context eq 'error';
1562 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1563 or return { 'error' => "unknown custnum $custnum" };
1567 my $cust_payby = $_;
1569 map { $_ => $cust_payby->$_ }
1570 qw( custpaybynum weight payby paymask paydate
1571 payname paystate paytype
1575 $cust_main->cust_payby
1583 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1584 return { 'error' => $session } if $context eq 'error';
1586 #XXX payinfo1 + payinfo2 for CHEK?
1587 #or take the opportunity to use separate, more well- named fields?
1589 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1590 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1591 # my $payinfo1 = $1;
1592 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1593 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1594 # my $payinfo2 = $1;
1595 # $payinfo = $payinfo1. '@'. $payinfo2;
1597 my $cust_payby = new FS::cust_payby {
1598 'custnum' => $custnum,
1599 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1600 paystate paytype payip
1604 my $error = $cust_payby->insert;
1606 return { 'error' => $error };
1608 return { 'custpaybynum' => $cust_payby->custpaybynum };
1616 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1617 return { 'error' => $session } if $context eq 'error';
1619 my $cust_payby = qsearchs('cust_payby', {
1620 'custnum' => $custnum,
1621 'custpaybynum' => $p->{'custpaybynum'},
1623 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1625 return { 'error' => $cust_payby->delete };
1631 my $session = _cache->get($p->{'session_id'})
1632 or return { 'error' => "Can't resume session" }; #better error message
1634 my $custnum = $session->{'custnum'};
1636 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1637 or return { 'error' => "unknown custnum $custnum" };
1639 my @errors = $cust_main->cancel( 'quiet'=>1 );
1641 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1643 return { 'error' => $error };
1650 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1651 return { 'error' => $session } if $context eq 'error';
1653 my $search = { 'custnum' => $custnum };
1654 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1655 my $cust_main = qsearchs('cust_main', $search )
1656 or return { 'error' => "unknown custnum $custnum" };
1658 my $conf = new FS::Conf;
1659 my $immutable = $conf->exists('selfservice_immutable-package');
1661 # the duplication below is necessary:
1662 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1663 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1664 # non-backwards-compatible change breaking the software of anyone using the API
1665 # instead of the stock selfservice
1666 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1667 if( $conf->exists('selfservice_server-view-wholesale') ) {
1668 return { 'svcnum' => $session->{'svcnum'},
1669 'custnum' => $custnum,
1670 'cust_pkg' => [ map {
1672 immutable => $immutable,
1673 part_pkg => [ map $_->hashref, $_->part_pkg ],
1675 [ map $_->hashref, $_->available_part_svc ],
1677 [ map { my $ref = { $_->hash,
1678 label => [ $_->label ],
1680 $ref->{_password} = $_->svc_x->_password
1681 if $context eq 'agent'
1682 && $conf->exists('agent-showpasswords')
1683 && $_->part_svc->svcdb eq 'svc_acct';
1688 } $cust_main->cust_pkg
1691 small_custview( $cust_main, $conf->config('countrydefault') ),
1692 'wholesale_view' => 1,
1693 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1694 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1695 'lnp' => $conf->exists('svc_phone-lnp'),
1699 { 'svcnum' => $session->{'svcnum'},
1700 'custnum' => $custnum,
1701 'cust_pkg' => [ map {
1702 my $primary_cust_svc = $_->primary_cust_svc;
1705 immutable => $immutable,
1706 pkg_label => $_->pkg_locale,
1707 status => $_->status,
1708 statuscolor => $_->statuscolor,
1710 [ map { $_->hashref }
1711 grep { $_->selfservice_access ne 'hidden' }
1712 $_->available_part_svc
1715 [ map { my $ref = { $_->hash,
1716 label => [ $_->label ],
1718 $ref->{_password} = $_->svc_x->_password
1719 if $context eq 'agent'
1720 && $conf->exists('agent-showpasswords')
1721 && $_->part_svc->svcdb eq 'svc_acct';
1722 $ref->{svchash} = { $_->svc_x->hash } if
1723 $_->part_svc->svcdb eq 'svc_phone';
1724 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1725 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1728 grep { $_->part_svc->selfservice_access ne 'hidden' }
1733 ? { $primary_cust_svc->hash,
1734 label => [ $primary_cust_svc->label ],
1735 finger => $primary_cust_svc->svc_x->finger, #uuh
1736 $primary_cust_svc->part_svc->hash,
1740 } $cust_main->ncancelled_pkgs
1743 small_custview( $cust_main, $conf->config('countrydefault') ),
1744 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1752 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1753 return { 'error' => $session } if $context eq 'error';
1755 my $conf = new FS::Conf;
1757 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1758 my $search = { 'custnum' => $custnum };
1759 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1760 my $cust_main = qsearchs('cust_main', $search )
1761 or return { 'error' => "unknown custnum $custnum" };
1763 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1764 if ( ! $pkgnum && $p->{'svcnum'} ) {
1765 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1766 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1770 my @cust_pkg_usage = ();
1771 foreach my $cust_pkg ( $p->{'ncancelled'}
1772 ? $cust_main->ncancelled_pkgs
1773 : $cust_main->unsuspended_pkgs ) {
1774 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1775 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1776 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1779 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1782 foreach (@cust_pkg_usage) {
1783 my $part = $_->part_pkg_usage;
1784 my $tag = $part->description . ($part->shared ? 1 : 0);
1785 my $row = $usage_pools{$tag}
1786 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1787 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1788 $row->[2] += $part->minutes; # minutes total
1790 } # otherwise just leave them empty
1792 if ( $p->{'svcdb'} ) {
1793 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1795 : ref($p->{'svcdb'}) eq 'ARRAY'
1796 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1797 : { $p->{'svcdb'} => 1 };
1798 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1801 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1804 my @svcs; # stuff to return to the client
1805 foreach my $cust_svc (@cust_svc) {
1806 my $svc_x = $cust_svc->svc_x;
1807 my($label, $value) = $cust_svc->label;
1808 my $part_svc = $cust_svc->part_svc;
1809 my $svcdb = $part_svc->svcdb;
1810 my $cust_pkg = $cust_svc->cust_pkg;
1811 my $part_pkg = $cust_pkg->part_pkg;
1814 'svcnum' => $cust_svc->svcnum,
1815 'display_svcnum' => $cust_svc->display_svcnum,
1819 'pkg_label' => $cust_pkg->pkg_locale,
1820 'pkg_status' => $cust_pkg->status,
1821 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1824 # would it make sense to put this in a svc_* method?
1826 if ( $svcdb eq 'svc_acct' ) {
1827 foreach (qw(username email finger seconds)) {
1828 $hash{$_} = $svc_x->$_;
1834 'upbytes' => display_bytecount($svc_x->upbytes),
1835 'downbytes' => display_bytecount($svc_x->downbytes),
1836 'totalbytes' => display_bytecount($svc_x->totalbytes),
1838 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1839 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1840 'recharge_upbytes' =>
1841 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1842 'recharge_downbytes' =>
1843 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1844 'recharge_totalbytes' =>
1845 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1850 } elsif ( $svcdb eq 'svc_dsl' ) {
1852 $hash{'phonenum'} = $svc_x->phonenum;
1853 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1854 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1855 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1858 $hash{'name'} = $cust_main->name;
1860 # no usage to hide here
1862 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1864 # could potentially show lots of things...
1865 $hash{'outbound'} = 1;
1866 $hash{'inbound'} = 0;
1867 if ( $svcdb eq 'svc_phone' ) {
1868 if ( $part_pkg->plan eq 'voip_inbound' ) {
1869 $hash{'outbound'} = 0;
1870 $hash{'inbound'} = 1;
1871 } elsif ( $part_pkg->option('selfservice_inbound_format')
1872 or $conf->config('selfservice-default_inbound_cdr_format')
1874 $hash{'inbound'} = 1;
1877 foreach (qw(inbound outbound)) {
1878 # hmm...we can't filter by status here, because there might
1879 # not be cdr_terminations at all. have to go by date.
1880 # find all since the last bill date.
1881 # XXX cdr types? we are going to need them.
1883 my $sum_cdr = $svc_x->sum_cdrs(
1884 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1885 'begin' => ($cust_pkg->last_bill || 0),
1887 'disable_charged_party' => 1,
1889 $hash{$_} = $sum_cdr->hashref;
1892 } # not hiding usage
1896 } # foreach $cust_svc
1899 'svcnum' => $session->{'svcnum'},
1900 'custnum' => $custnum,
1901 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1902 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1905 map { $usage_pools{$_} }
1909 'hide_usage' => $hide_usage,
1914 sub _customer_svc_x {
1915 my($custnum, $svcnum, $table) = (shift, shift, shift);
1916 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1918 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1919 my $search = " AND custnum = $1";
1920 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1923 'table' => ($table || 'svc_acct'),
1924 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1925 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1926 #'LEFT JOIN cust_main USING ( custnum ) ',
1927 'hashref' => $hashref,
1928 'extra_sql' => $search, #important
1933 sub svc_status_html {
1936 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1937 return { 'error' => $session } if $context eq 'error';
1939 #XXX only svc_dsl for now
1940 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1941 or return { 'error' => "Service not found" };
1943 my $html = $svc_x->getstatus_html;
1945 return { 'html' => $html };
1949 sub svc_status_hash {
1952 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1953 return { 'error' => $session } if $context eq 'error';
1955 #XXX only svc_acct for now
1956 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1957 or return { 'error' => "Service not found" };
1959 my ( $html, $hashref ) = $svc_x->export_getstatus;
1964 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1965 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1966 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1967 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1968 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1971 my( $p, $method ) = @_;
1973 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1974 return { 'error' => $session } if $context eq 'error';
1976 #XXX only svc_acct for now
1977 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1978 or return { 'error' => "Service not found" };
1980 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1982 my $error = $svc_x->$method($p); #$p? returns error?
1983 return { 'error' => $error } if $error;
1985 return {}; #? { 'error' => '' }
1989 sub acct_forward_info {
1992 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1993 return { 'error' => $session } if $context eq 'error';
1995 my $svc_forward = _customer_svc_x( $custnum,
1996 { 'srcsvc' => $p->{'svcnum'} },
1999 or return { 'error' => '',
2003 return { 'error' => '',
2004 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2009 sub process_acct_forward {
2011 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2012 return { 'error' => $session } if $context eq 'error';
2014 my $old = _customer_svc_x( $custnum,
2015 { 'srcsvc' => $p->{'svcnum'} },
2019 if ( $p->{'dst'} eq '' ) {
2021 my $error = $old->delete;
2022 return { 'error' => $error };
2024 return { 'error' => '' };
2027 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2028 'dst' => $p->{'dst'},
2033 $new->svcnum($old->svcnum);
2034 my $cust_svc = $old->cust_svc;
2035 $new->svcpart($old->svcpart);
2036 $new->pkgnuym($old->pkgnum);
2037 $error = $new->replace($old);
2039 my $conf = new FS::Conf;
2040 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2042 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2043 or return { 'error' => 'No service' }; #how would we even get here?
2045 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2047 $error = $new->insert;
2050 return { 'error' => $error };
2054 sub list_dsl_devices {
2057 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2058 return { 'error' => $session } if $context eq 'error';
2060 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2061 or return { 'error' => "Service not found" };
2064 'devices' => [ map {
2065 +{ 'mac_addr' => $_->mac_addr };
2066 } $svc_dsl->dsl_device
2072 sub add_dsl_device {
2075 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2076 return { 'error' => $session } if $context eq 'error';
2078 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2079 or return { 'error' => "Service not found" };
2081 return { 'error' => 'No MAC address supplied' }
2082 unless length($p->{'mac_addr'});
2084 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2085 'mac_addr' => scalar($p->{'mac_addr'}),
2087 my $error = $dsl_device->insert;
2088 return { 'error' => $error };
2092 sub delete_dsl_device {
2095 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2096 return { 'error' => $session } if $context eq 'error';
2098 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2099 or return { 'error' => "Service not found" };
2101 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2102 'mac_addr' => scalar($p->{'mac_addr'}),
2105 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2107 my $error = $dsl_device->delete;
2108 return { 'error' => $error };
2114 _usage_details( \&_port_graph, $p,
2115 'svcdb' => 'svc_port',
2120 my($svc_port, $begin, $end) = @_;
2122 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2123 push @usage, { 'png' => $pngOrError };
2127 sub _list_svc_usage {
2128 my($svc_acct, $begin, $end) = @_;
2130 foreach my $part_export (
2131 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2132 qw( sqlradius sqlradius_withdomain )
2134 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2139 sub list_svc_usage {
2140 _usage_details(\&_list_svc_usage, @_);
2143 sub _list_support_usage {
2144 my($svc_acct, $begin, $end) = @_;
2146 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2147 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2149 push @usage, { 'seconds' => $_->seconds,
2150 'support' => $_->support,
2151 '_date' => $_->_date,
2152 'id' => $_->transaction_id,
2153 'creator' => $_->creator,
2154 'subject' => $_->subject,
2155 'status' => $_->status,
2156 'ticketid' => $_->ticketid,
2162 sub list_support_usage {
2163 _usage_details(\&_list_support_usage, @_);
2166 sub _list_cdr_usage {
2167 # XXX CDR type support...
2168 # XXX any way to do a paged search on this?
2169 # we have to return the results all at once...
2170 my($svc_x, $begin, $end, %opt) = @_;
2171 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2175 'disable_charged_party' => 1,
2180 sub list_cdr_usage {
2182 _usage_details( \&_list_cdr_usage, $p );
2185 sub _usage_details {
2186 my($callback, $p, %opt) = @_;
2187 my $conf = FS::Conf->new;
2189 if ( $conf->exists('selfservice_hide-usage') ) {
2190 return { 'error' => 'Viewing usage is not allowed.' };
2193 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2194 return { 'error' => $session } if $context eq 'error';
2196 my $search = { 'svcnum' => $p->{'svcnum'} };
2197 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2199 my $cust_svc = qsearchs( 'cust_svc', $search );
2200 return { 'error' => 'No service selected in list_svc_usage' }
2203 my $svc_x = $cust_svc->svc_x;
2204 my $svcdb = $svc_x->table;
2205 my $cust_pkg = $cust_svc->cust_pkg;
2206 my $freq = $cust_pkg->part_pkg->freq;
2209 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2211 if ( $p->{inbound} ) {
2212 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2213 || $conf->config('selfservice-default_inbound_cdr_format')
2214 || 'source_default';
2215 $callback_opt{inbound} = 1;
2217 $format = $cust_pkg->part_pkg->option('selfservice_format')
2218 || $conf->config('selfservice-default_cdr_format')
2222 $callback_opt{format} = $format;
2223 $callback_opt{use_clid} = 1;
2224 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2227 my $start = $cust_pkg->setup;
2228 #my $end = $cust_pkg->bill; # or time?
2231 unless ( $p->{beginning} ) {
2232 $p->{beginning} = $cust_pkg->last_bill;
2233 $p->{ending} = $end;
2236 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2237 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2239 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2243 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2244 # ugly kludge, I know
2245 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2246 if (defined $delete_col) {
2247 delete($_->[$delete_col]) foreach ($header, @usage);
2251 #kinda false laziness with FS::cust_main::bill, but perhaps
2252 #we should really change this bit to DateTime and DateTime::Duration
2254 #change this bit to use Date::Manip? CAREFUL with timezones (see
2255 # mailing list archive)
2256 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2257 (localtime($p->{ending}) )[0,1,2,3,4,5];
2258 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2259 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2261 if ( $freq =~ /^\d+$/ ) {
2263 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2265 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2266 } elsif ( $freq =~ /^(\d+)w$/ ) {
2268 $nmday += $weeks * 7;
2269 $pmday -= $weeks * 7;
2270 } elsif ( $freq =~ /^(\d+)d$/ ) {
2274 } elsif ( $freq =~ /^(\d+)h$/ ) {
2279 return { 'error' => "unparsable frequency: ". $freq };
2282 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2283 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2287 'svcnum' => $p->{svcnum},
2288 'beginning' => $p->{beginning},
2289 'ending' => $p->{ending},
2290 'inbound' => $p->{inbound},
2291 'previous' => ($previous > $start) ? $previous : $start,
2292 'next' => ($next < $end) ? $next : $end,
2293 'header' => $header,
2301 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2302 return { 'error' => $session } if $context eq 'error';
2304 my $search = { 'custnum' => $custnum };
2305 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2306 my $cust_main = qsearchs('cust_main', $search )
2307 or return { 'error' => "unknown custnum $custnum" };
2309 my $status = $cust_main->status;
2311 my %order_pkg_options = ();
2312 if ( $p->{locationnum} > 0 ) {
2313 $order_pkg_options{locationnum} = delete($p->{locationnum});
2314 } elsif ( $p->{address1} ) {
2315 $order_pkg_options{'cust_location'} = new FS::cust_location {
2316 map { $_ => $p->{$_} }
2317 qw( address1 address2 city county state zip country )
2321 #false laziness w/ClientAPI/Signup.pm
2323 my $cust_pkg = new FS::cust_pkg ( {
2324 'custnum' => $custnum,
2325 'pkgpart' => $p->{'pkgpart'},
2326 'quantity' => $p->{'quantity'} || 1,
2328 my $error = $cust_pkg->check;
2329 return { 'error' => $error } if $error;
2332 unless ( $p->{'svcpart'} eq 'none' ) {
2336 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2338 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2339 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2340 $svcdb = $part_svc->svcdb;
2342 $svcdb = 'svc_acct';
2344 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2347 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2348 'svc_domain' => [ qw( domain ) ],
2349 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2350 'svc_external' => [ qw( id title ) ],
2351 'svc_pbx' => [ qw( id title ) ],
2354 my $svc_x = "FS::$svcdb"->new( {
2355 'svcpart' => $svcpart,
2356 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2359 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2362 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2363 my $acct_snarf = new FS::acct_snarf ( {
2364 'machine' => $p->{"snarf_machine$snarfnum"},
2365 'protocol' => $p->{"snarf_protocol$snarfnum"},
2366 'username' => $p->{"snarf_username$snarfnum"},
2367 '_password' => $p->{"snarf_password$snarfnum"},
2370 push @acct_snarf, $acct_snarf;
2372 $svc_x->child_objects( \@acct_snarf );
2375 my $y = $svc_x->setdefault; # arguably should be in new method
2376 return { 'error' => $y } if $y && !ref($y);
2378 $error = $svc_x->check;
2379 return { 'error' => $error } if $error;
2385 $error = $cust_main->order_pkg(
2386 'cust_pkg' => $cust_pkg,
2391 return { 'error' => $error } if $error;
2393 my $conf = new FS::Conf;
2394 if ( $conf->exists('signup_server-realtime') ) {
2396 my $bill_error = _do_bop_realtime( $cust_main, $status );
2399 $cust_pkg->cancel('quiet'=>1);
2402 $cust_pkg->reexport;
2406 $cust_pkg->reexport;
2409 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2411 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2418 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2419 return { 'error' => $session } if $context eq 'error';
2421 my $conf = new FS::Conf;
2422 my $immutable = $conf->exists('selfservice_immutable-package');
2423 return { 'error' => "Package modification disabled" } if $immutable;
2425 my $search = { 'custnum' => $custnum };
2426 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2427 my $cust_main = qsearchs('cust_main', $search )
2428 or return { 'error' => "unknown custnum $custnum" };
2430 my $status = $cust_main->status;
2431 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2432 or return { 'error' => "unknown package $p->{pkgnum}" };
2434 #if someone does need self-service package change of suspended packages,
2435 # figure out how to be more discriminating
2436 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2437 if $cust_pkg->status eq 'suspended';
2439 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2440 'quantity' => $p->{'quantity'} || 1,
2443 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2444 unless ref($err_or_cust_pkg);
2446 if ( $conf->exists('signup_server-realtime') ) {
2448 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2451 $err_or_cust_pkg->suspend;
2454 $err_or_cust_pkg->reexport;
2458 $err_or_cust_pkg->reexport;
2461 return { error => '', pkgnum => $cust_pkg->pkgnum };
2465 sub order_recharge {
2468 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2469 return { 'error' => $session } if $context eq 'error';
2471 my $search = { 'custnum' => $custnum };
2472 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2473 my $cust_main = qsearchs('cust_main', $search )
2474 or return { 'error' => "unknown custnum $custnum" };
2476 my $status = $cust_main->status;
2477 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2478 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2480 my $svc_x = $cust_svc->svc_x;
2481 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2484 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2485 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2486 recharge_totalbytes );
2487 my $amount = $part_pkg->option('recharge_amount', 1);
2489 my ($l, $v, $d) = $cust_svc->label; # blah
2490 my $pkg = "Recharge $v";
2492 my $bill_error = $cust_main->charge($amount, $pkg,
2493 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2494 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2495 $part_pkg->taxclass); #meh
2497 my $conf = new FS::Conf;
2498 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2500 $bill_error = _do_bop_realtime( $cust_main, $status );
2505 my $error = $svc_x->recharge (\%vhash);
2506 return { 'error' => $error } if $error;
2510 my $error = $bill_error;
2511 $error ||= $svc_x->recharge (\%vhash);
2512 return { 'error' => $error } if $error;
2515 return { error => '', svc => $cust_svc->part_svc->svc };
2519 sub _do_bop_realtime {
2520 my ($cust_main, $status, %opt) = @_;
2522 my $old_balance = $cust_main->balance;
2525 my $bill_error = $cust_main->bill(
2526 'return_bill' => \@cust_bill,
2529 $bill_error ||= $cust_main->apply_payments_and_credits;
2531 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2533 if ( $cust_main->balance > $old_balance
2534 && $cust_main->balance > 0
2535 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2538 unless ( $opt{'no_invoice_void'} ) {
2540 #this used to apply a credit, but now we can void invoices...
2541 foreach my $cust_bill (@cust_bill) {
2542 my $voiderror = $cust_bill->void('automatic payment failed');
2543 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2548 return { 'error' => '_decline', 'bill_error' => $bill_error };
2557 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2558 return { 'error' => $session } if $context eq 'error';
2560 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2561 or return { 'error' => "unknown custnum $custnum" };
2563 my @cust_pkg = sort { $a->bill <=> $b->bill }
2564 grep { $_->part_pkg->freq ne '0' }
2565 $cust_main->ncancelled_pkgs;
2567 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2569 my $total = $cust_main->balance;
2572 my $bill = $_->bill;
2573 $total += $_->part_pkg->base_recur($_, \$bill);
2574 my $renew_date = $_->part_pkg->add_freq($_->bill);
2576 'pkgnum' => $_->pkgnum,
2577 'amount' => sprintf('%.2f', $total),
2578 'bill_date' => $_->bill,
2579 'bill_date_pretty' => time2str('%x', $_->bill),
2580 'renew_date' => $renew_date,
2581 'renew_date_pretty' => time2str('%x', $renew_date),
2582 'expire_date' => $_->expire,
2583 'expire_date_pretty' => time2str('%x', $_->expire),
2588 return { 'dates' => \@array };
2592 sub payment_info_renew_info {
2594 my $renew_info = renew_info($p);
2595 my $payment_info = payment_info($p);
2596 return { %$renew_info,
2604 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2605 return { 'error' => $session } if $context eq 'error';
2607 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2608 or return { 'error' => "unknown custnum $custnum" };
2610 my $date = $p->{'date'};
2614 #freeside-daily -n -d $date fs_daily $custnum
2615 $cust_main->bill_and_collect( 'time' => $date,
2616 'invoice_time' => $now,
2617 'actual_time' => $now,
2618 'check_freq' => '1d',
2621 return { 'error' => '' };
2627 my $session = _cache->get($p->{'session_id'})
2628 or return { 'error' => "Can't resume session" }; #better error message
2630 my $custnum = $session->{'custnum'};
2632 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2633 or return { 'error' => "unknown custnum $custnum" };
2635 my $conf = new FS::Conf;
2637 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2638 or return { 'error' => 'Permission denied' };
2640 my $pkgnum = $p->{'pkgnum'};
2642 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2643 'pkgnum' => $pkgnum, } )
2644 or return { 'error' => "unknown pkgnum $pkgnum" };
2646 my $error = $cust_pkg->suspend(reason => $reasonnum);
2647 return { 'error' => $error };
2653 my $session = _cache->get($p->{'session_id'})
2654 or return { 'error' => "Can't resume session" }; #better error message
2656 my $custnum = $session->{'custnum'};
2658 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2659 or return { 'error' => "unknown custnum $custnum" };
2661 my $pkgnum = $p->{'pkgnum'};
2663 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2664 'pkgnum' => $pkgnum, } )
2665 or return { 'error' => "unknown pkgnum $pkgnum" };
2667 my $error = $cust_pkg->cancel('quiet' => 1);
2668 return { 'error' => $error };
2672 sub provision_phone {
2675 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2677 #editing an existing phone number
2678 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2679 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2680 return { 'error' => $session } if $context eq 'error';
2682 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2683 return { 'error' => 'service not found' } unless $svc_phone;
2684 return { 'error' => 'invalid svcnum' }
2685 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2687 $svc_phone->email($p->{'email'})
2688 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2689 $svc_phone->forwarddst($p->{'forwarddst'})
2690 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2691 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2692 return { 'error' => $svc_phone->replace };
2696 unless ( $p->{'lnp'} ) {
2697 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2698 $p->{'lnp_status'} = "portingin";
2699 return _provision( 'FS::svc_phone',
2700 [qw(lnp_desired_due_date lnp_other_provider
2701 lnp_other_provider_account phonenum countrycode lnp_status)],
2702 [qw(phonenum countrycode)],
2708 # single DID order (the usual case)
2709 unless (scalar(@bulkdid)) {
2710 return _provision( 'FS::svc_phone',
2711 [qw(phonenum countrycode)],
2712 [qw(phonenum countrycode)],
2718 # bulk DID order case
2720 foreach my $did ( @bulkdid ) {
2721 $did =~ s/[^0-9]//g;
2722 $error = _provision( 'FS::svc_phone',
2723 [qw(phonenum countrycode)],
2724 [qw(phonenum countrycode)],
2726 'pkgnum' => $p->{'pkgnum'},
2727 'svcpart' => $p->{'svcpart'},
2729 'countrycode' => $p->{'countrycode'},
2730 'session_id' => $p->{'session_id'},
2733 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2735 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2740 warn "provision_pbx called\n"
2743 warn "provision_pbx calling _provision\n"
2745 _provision( 'FS::svc_pbx',
2746 [qw(id title max_extensions max_simultaneous ip_addr)],
2747 [qw(id title max_extensions max_simultaneous ip_addr)],
2753 sub provision_acct {
2755 warn "provision_acct called\n"
2758 return { 'error' => gettext('passwords_dont_match') }
2759 if $p->{'_password'} ne $p->{'_password2'};
2760 return { 'error' => gettext('empty_password') }
2761 unless length($p->{'_password'});
2763 if ($p->{'domsvc'}) {
2764 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2765 qw ( svcpart pkgnum ) );
2766 return { 'error' => gettext('invalid_domain') }
2767 unless ($domains{$p->{'domsvc'}});
2770 warn "provision_acct calling _provision\n"
2772 _provision( 'FS::svc_acct',
2773 [qw(username _password domsvc)],
2774 [qw(username _password domsvc)],
2780 sub provision_external {
2782 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2783 _provision( 'FS::svc_external',
2791 sub provision_forward {
2793 _provision( 'FS::svc_forward',
2794 ['srcsvc','src','dstsvc','dst'],
2801 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2802 warn "_provision called for $class\n"
2805 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2806 return { 'error' => $session } if $context eq 'error';
2808 my $search = { 'custnum' => $custnum };
2809 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2810 my $cust_main = qsearchs('cust_main', $search )
2811 or return { 'error' => "unknown custnum $custnum" };
2813 my $pkgnum = $p->{'pkgnum'};
2815 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2817 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2818 'pkgnum' => $pkgnum,
2820 or return { 'error' => "unknown pkgnum $pkgnum" };
2822 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2824 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2825 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2827 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2828 if $class ne 'FS::'. $part_svc->svcdb;
2830 warn "creating $class record\n"
2832 my $svc_x = $class->new( {
2833 'pkgnum' => $p->{'pkgnum'},
2834 'svcpart' => $p->{'svcpart'},
2835 map { $_ => $p->{$_} } @$fields
2838 my %insert_args = ();
2839 #i shouldn't be a special case here (pass an option or something)
2840 if ( $class eq 'FS::svc_phone'
2841 && grep length($p->{$_}), @location_editable_fields
2844 $insert_args{'cust_location'} = new FS::cust_location {
2845 map { $_ => $p->{$_} } @location_editable_fields
2849 warn "inserting $class record\n"
2851 my $error = $svc_x->insert(%insert_args);
2854 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2856 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2859 my $return = { 'svc' => $part_svc->svc,
2861 map { $_ => $svc_x->get($_) } @$return_fields
2863 warn "_provision returning ". Dumper($return). "\n"
2872 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2873 return { 'error' => $session } if $context eq 'error';
2875 my $search = { 'custnum' => $custnum };
2876 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2877 my $cust_main = qsearchs('cust_main', $search )
2878 or return { 'error' => "unknown custnum $custnum" };
2880 my $pkgnum = $p->{'pkgnum'};
2882 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2883 'pkgnum' => $pkgnum,
2885 or return { 'error' => "unknown pkgnum $pkgnum" };
2887 my $svcpart = $p->{'svcpart'};
2889 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2890 'svcpart' => $svcpart, } )
2891 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2892 my $part_svc = $pkg_svc->part_svc;
2894 my $conf = new FS::Conf;
2897 'svc' => $part_svc->svc,
2898 'svcdb' => $part_svc->svcdb,
2899 'pkgnum' => $pkgnum,
2900 'svcpart' => $svcpart,
2901 'custnum' => $custnum,
2903 'security_phrase' => 0, #XXX !
2904 'svc_acct_pop' => [], #XXX !
2906 'init_popstate' => '',
2911 small_custview( $cust_main, $conf->config('countrydefault') ),
2915 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2916 && $ret->{'svcdb'} eq 'svc_phone') {
2917 $ret->{'svcnum'} = $p->{'svcnum'};
2918 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2919 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2920 $ret->{'email'} = $svc_phone->email;
2921 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2925 if ($ret->{'svcdb'} eq 'svc_forward') {
2926 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2932 sub unprovision_svc {
2935 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2936 return { 'error' => $session } if $context eq 'error';
2938 my $search = { 'custnum' => $custnum };
2939 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2940 my $cust_main = qsearchs('cust_main', $search )
2941 or return { 'error' => "unknown custnum $custnum" };
2943 my $svcnum = $p->{'svcnum'};
2945 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2946 or return { 'error' => "unknown svcnum $svcnum" };
2948 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2949 unless $cust_svc->cust_pkg->custnum == $custnum;
2951 my $conf = new FS::Conf;
2953 return { 'svc' => $cust_svc->part_svc->svc,
2954 'error' => $cust_svc->cancel,
2956 small_custview( $cust_main, $conf->config('countrydefault') ),
2961 sub myaccount_passwd {
2963 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2964 return { 'error' => $session } if $context eq 'error';
2966 return { 'error' => "New passwords don't match." }
2967 if $p->{'new_password'} ne $p->{'new_password2'};
2969 return { 'error' => 'Enter new password' }
2970 unless length($p->{'new_password'});
2972 #my $search = { 'custnum' => $custnum };
2973 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2974 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2975 my $search = " AND custnum = $1";
2976 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2978 my $svc_acct = qsearchs( {
2979 'table' => 'svc_acct',
2980 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2981 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2982 'LEFT JOIN cust_main USING ( custnum ) ',
2983 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2984 'extra_sql' => $search, #important
2986 or return { 'error' => "Service not found" };
2990 my $conf = new FS::Conf;
2992 return { 'error' => 'Incorrect current password.' }
2993 if ( exists($p->{'old_password'})
2994 || $conf->exists('selfservice-password_change_oldpass')
2996 && ! $svc_acct->check_password($p->{'old_password'});
2998 # should move password length checks into is_password_allowed
2999 $error = 'Password too short.'
3000 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
3001 $error = 'Password too long.'
3002 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
3004 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3005 || $svc_acct->set_password($p->{'new_password'})
3006 || $svc_acct->replace();
3008 #regular pw change in self-service should change contact pw too, otherwise its
3009 #way too confusing. hell its confusing they're separate at all, but alas.
3010 #need to support the "ISP provides email that's used as a contact email" case
3012 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3013 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3014 custnum => $custnum,
3015 selfservice_access => 'Y',
3019 #svc_acct was successful but this one returns an error? "shouldn't happen"
3020 #don't recheck is_password_allowed here; if the svc_acct password was
3021 #legal, that's good enough
3022 $error ||= $contact->change_password($p->{'new_password'});
3025 my($label, $value) = $svc_acct->cust_svc->label;
3027 return { 'error' => $error,
3037 my $info = skin_info($p);
3039 my $conf = new FS::Conf;
3040 my $verification = $conf->config('selfservice-password_reset_verification')
3041 or return { %$info, 'error' => 'Password resets disabled' };
3046 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3048 $contact = FS::contact->by_selfservice_email($p->{'email'});
3051 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3052 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3055 #also look for an svc_acct, otherwise it would be super confusing
3057 my($username, $domain) = split('@', $p->{'email'});
3058 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3059 if ( $svc_domain ) {
3060 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3061 'domsvc' => $svc_domain->svcnum }
3064 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3065 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3067 #precaution: don't change svc_acct password not part of the same
3068 # customer as contact
3069 $svc_acct = '' if ! $cust_pkg
3070 || $cust_pkg->custnum != $cust_main->custnum;
3075 return { %$info, 'error' => 'Email address not found' }
3076 unless $contact || $svc_acct;
3078 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3080 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3081 or return { %$info, 'error' => 'Account not found' };
3083 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3084 'domsvc' => $svc_domain->svcnum }
3086 or return { %$info, 'error' => 'Account not found' };
3088 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3089 or return { %$info, 'error' => 'Account not found' };
3091 $cust_main = $cust_pkg->cust_main;
3095 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3096 if ! $cust_main && $verification ne 'email';
3099 'email' => sub { 1; },
3101 my( $p, $cust_main ) = @_;
3102 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3103 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3106 my( $p, $cust_main ) = @_;
3107 my $cust_pay = qsearchs({
3108 'table' => 'cust_pay',
3109 'hashref' => { 'custnum' => $cust_main->custnum },
3110 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3114 $p->{'amount'} == $cust_pay->paid;
3117 my( $p, $cust_main ) = @_;
3118 $p->{'zip'} eq $cust_main->zip
3119 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3123 foreach my $verify ( split(',', $verification) ) {
3125 &{ $verify{$verify} }( $p, $cust_main )
3126 or return { %$info, 'error' => 'Account not found' };
3130 #okay, we're verified
3134 my $error = $contact->send_reset_email(
3135 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3139 return { %$info, 'error' => $error }; #????
3142 } elsif ( $svc_acct ) {
3144 #create a unique session
3146 my $reset_session = {
3147 'svcnum' => $svc_acct->svcnum,
3148 'agentnum' => $svc_acct->cust_main->agentnum,
3151 my $timeout = '1 hour'; #?
3153 my $reset_session_id;
3155 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3156 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3159 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3163 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3164 $cust_main->agentnum);
3165 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3166 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3168 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3169 my $error = $msg_template->send( 'cust_main' => $cust_main,
3170 'object' => $svc_acct,
3171 'substitutions' => {
3172 'session_id' => $reset_session_id,
3176 return { %$info, 'error' => $error }; #????
3181 return { %$info, 'error' => '' };
3184 sub check_reset_passwd {
3187 my $conf = new FS::Conf;
3188 my $verification = $conf->config('selfservice-password_reset_verification')
3189 or return { 'error' => 'Password resets disabled' };
3191 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3192 or return { 'error' => "Can't resume session" }; #better error message
3194 if ( $reset_session->{'svcnum'} ) {
3196 my $svcnum = $reset_session->{'svcnum'};
3198 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3199 or return { 'error' => "Service not found" };
3201 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3202 my $info = skin_info($p);
3206 'session_id' => $p->{'session_id'},
3207 'username' => $svc_acct->username,
3210 } elsif ( $reset_session->{'contactnum'} ) {
3212 my $contactnum = $reset_session->{'contactnum'};
3214 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3215 or return { 'error' => "Contact not found" };
3217 my @contact_email = $contact->contact_email;
3218 return { 'error' => 'No contact email' } unless @contact_email;
3220 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3221 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3222 if scalar(@cust_contact) == 1;
3223 my $info = skin_info($p);
3227 'session_id' => $p->{'session_id'},
3228 'email' => $contact_email[0]->email, #the first?
3233 return { 'error' => 'No svcnum or contactnum in session' }; #??
3239 sub process_reset_passwd {
3242 my $conf = new FS::Conf;
3243 my $verification = $conf->config('selfservice-password_reset_verification')
3244 or return { 'error' => 'Password resets disabled' };
3246 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3247 or return { 'error' => "Can't resume session" }; #better error message
3252 if ( $reset_session->{'svcnum'} ) {
3254 my $svcnum = $reset_session->{'svcnum'};
3256 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3257 or return { 'error' => "Service not found" };
3259 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3260 $info ||= skin_info($p);
3265 if ( $reset_session->{'contactnum'} ) {
3267 my $contactnum = $reset_session->{'contactnum'};
3269 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3270 or return { 'error' => "Contact not found" };
3272 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3273 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3274 if scalar(@cust_contact) == 1;
3275 $info ||= skin_info($p);
3279 return { %$info, 'error' => "New passwords don't match." }
3280 if $p->{'new_password'} ne $p->{'new_password2'};
3282 return { %$info, 'error' => 'Enter new password' }
3283 unless length($p->{'new_password'});
3287 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3288 || $svc_acct->set_password($p->{'new_password'})
3289 || $svc_acct->replace();
3291 return { %$info, 'error' => $error } if $error;
3293 #my($label, $value) = $svc_acct->cust_svc->label;
3294 #return { 'error' => $error,
3295 # #'label' => $label,
3296 # #'value' => $value,
3303 my $error = $contact->is_password_allowed($p->{'new_password'})
3304 || $contact->change_password($p->{'new_password'});
3306 return { %$info, 'error' => $error }; # if $error;
3310 #password changed ,so remove session, don't want it reused
3311 _cache->remove($p->{'session_id'});
3313 return { %$info, 'error' => '' };
3319 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3320 return { 'error' => $session } if $context eq 'error';
3323 if ( $session->{'pkgnum'} ) {
3325 #tickets for specific service with pkg-balances on
3326 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3327 'pkgnum' => $session->{'pkgnum'} })
3328 or return { 'error' => 'unknown package' };
3329 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3330 push @tickets, $cust_svc->tickets( $p->{status} );
3335 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3336 or return { 'error' => "unknown custnum $custnum" };
3338 @tickets = $cust_main->tickets( $p->{status} );
3341 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3342 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3343 my $conf = new FS::Conf;
3344 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3348 ($a->{'_selfservice_priority'} eq '') <=>
3349 ($b->{'_selfservice_priority'} eq '')
3352 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3358 +{ tickets => \@tickets };
3365 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3366 return { 'error' => $session } if $context eq 'error';
3368 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3369 FS::TicketSystem->init();
3371 my $conf = new FS::Conf;
3372 my $queue = $p->{'queue'}
3373 || $conf->config('ticket_system-selfservice_queueid')
3374 || $conf->config('ticket_system-default_queueid');
3376 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3377 my $err_or_ticket = FS::TicketSystem->create_ticket(
3378 '', #create RT session based on FS CurrentUser (fs_selfservice)
3380 'custnum' => $custnum,
3381 'svcnum' => $session->{'svcnum'},
3382 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3385 if ( ref($err_or_ticket) ) {
3386 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3388 return { 'error' => '',
3389 'ticket_id' => $err_or_ticket->id,
3392 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3394 return { 'error' => $err_or_ticket };
3402 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3403 return { 'error' => $session } if $context eq 'error';
3405 return { error => 'requested format not implemented' }
3406 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3408 my $conf = new FS::Conf;
3409 my $age_threshold = 0;
3410 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3411 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3413 my $search = { 'custnum' => $custnum };
3414 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3415 my $cust_main = qsearchs('cust_main', $search )
3416 or return { 'error' => "unknown custnum $custnum" };
3418 # does it make more sense to just run one sql query for this instead of all the
3419 # insanity below? would increase performance greately for large data sets?
3421 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3422 my @part_svc = $cust_pkg->part_svc;
3423 foreach my $part_svc ( @part_svc ) {
3424 if($part_svc->svcdb eq 'svc_phone'){
3425 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3426 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3427 push @svc_phone, $cust_pkg_svc->svc_x
3428 if $cust_pkg_svc->date_inserted >= $age_threshold;
3436 my($xls_r,$xls_c) = (0,0);
3439 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3440 if($p->{'format'} eq 'csv') {
3441 $csv = new Text::CSV_XS { 'always_quote' => 1,
3444 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3445 $content .= $csv->string;
3447 elsif($p->{'format'} eq 'xls') {
3448 my $XLS1 = new IO::Scalar \$content;
3449 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3450 or return { 'error' => "Error opening .xls file: $!" };
3451 $xls = $xls_workbook->add_worksheet('DIDs');
3452 foreach ( @fields ) {
3453 $xls->write(0,$xls_c++,$_);
3458 foreach my $svc_phone ( @svc_phone ) {
3459 my @cols = map { $svc_phone->$_ } @fields;
3460 if($p->{'format'} eq 'csv') {
3461 return { 'error' => 'Unable to create CSV' }
3462 unless $csv->combine(@cols);
3463 $content .= $csv->string;
3465 elsif($p->{'format'} eq 'xls') {
3468 $xls->write($xls_r,$xls_c++,$_);
3474 $xls_workbook->close() if $p->{'format'} eq 'xls';
3476 { content => $content, format => $p->{'format'}, };
3481 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3482 return { 'error' => $session } if $context eq 'error';
3484 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3485 # FS::TicketSystem->init();
3486 # return { 'error' => 'get_ticket configuration error' }
3487 # if $FS::TicketSystem::system ne 'RT_Internal';
3489 # check existence and ownership as part of this
3490 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3491 my $rt_session = FS::TicketSystem->session('');
3492 my $Ticket = FS::TicketSystem->get_ticket_object(
3494 ticket_id => $p->{'ticket_id'},
3497 return { 'error' => 'ticket not found' } if !$Ticket;
3499 if ( length( $p->{'subject'} || '' ) ) {
3501 if ( $p->{'subject'} ne $Ticket->Subject ) {
3502 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3503 return { 'error' => "unable to set subject: $msg" } if !$val;
3507 if(length($p->{'reply'})) {
3508 my @err_or_res = FS::TicketSystem->correspond_ticket(
3510 'ticket_id' => $p->{'ticket_id'},
3511 'content' => $p->{'reply'},
3514 return { 'error' => 'unable to reply to ticket' }
3515 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3518 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3519 my $err_or_ticket = FS::TicketSystem->get_ticket(
3521 'ticket_id' => $p->{'ticket_id'},
3524 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3525 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3527 return { 'error' => $err_or_ticket };
3530 my @custs = @{$err_or_ticket->{'custs'}};
3531 my @txns = @{$err_or_ticket->{'txns'}};
3534 # superseded by check in get_ticket_object
3535 #return { 'error' => 'invalid ticket requested' }
3536 #unless grep($_ eq $custnum, @custs);
3538 foreach my $txn ( @txns ) {
3539 push @filtered_txns, $txn
3540 if ($txn->{'type'} eq 'EmailRecord'
3541 || $txn->{'type'} eq 'Correspond'
3542 || $txn->{'type'} eq 'Create');
3545 warn "$me get_ticket: successful: \n"
3547 return { 'error' => '',
3548 'transactions' => \@filtered_txns,
3549 'ticket_fields' => $err_or_ticket->{'fields'},
3550 'ticket_id' => $p->{'ticket_id'},
3554 sub adjust_ticket_priority {
3556 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3557 return { 'error' => $session } if $context eq 'error';
3559 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3560 # FS::TicketSystem->init;
3561 my $ss_priority = FS::TicketSystem->selfservice_priority;
3563 return { 'error' => 'adjust_ticket_priority configuration error' }
3564 if $FS::TicketSystem::system ne 'RT_Internal'
3567 my $values = $p->{'values'}; #hashref, id => priority value
3570 foreach my $id (keys %$values) {
3571 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3572 my $Ticket = FS::TicketSystem->get_ticket_object('',
3574 'custnum' => $custnum,
3577 $ticket_error{$id} = 'ticket not found';
3581 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3582 # We're not going to implement it for RT_External.
3583 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3584 my $new_value = $values->{$id};
3585 next if $old_value eq $new_value;
3587 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3589 # AddCustomFieldValue works fine (replacing any existing value) if it's
3590 # a single-valued custom field, which it should be. If it's not, you're
3591 # doing something wrong.
3593 if ( length($new_value) ) {
3594 ($val, $msg) = $Ticket->AddCustomFieldValue(
3595 Field => $ss_priority,
3596 Value => $new_value,
3600 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3601 Field => $ss_priority,
3602 Value => $old_value,
3606 $ticket_error{$id} = $msg if !$val;
3607 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3609 return { 'error' => '',
3610 'ticket_error' => \%ticket_error,
3611 %{ customer_info($p) } # send updated customer info back
3617 sub _custoragent_session_custnum {
3620 my($context, $session, $custnum);
3621 if ( $p->{'session_id'} ) {
3623 $context = 'customer';
3624 $session = _cache->get($p->{'session_id'})
3625 or return ( 'error' => "Can't resume session" ); #better error message
3626 $custnum = $session->{'custnum'};
3628 } elsif ( $p->{'agent_session_id'} ) {
3631 my $agent_cache = new FS::ClientAPI_SessionCache( {
3632 'namespace' => 'FS::ClientAPI::Agent',
3634 $session = $agent_cache->get($p->{'agent_session_id'})
3635 or return ( 'error' => "Can't resume session" ); #better error message
3636 $custnum = $p->{'custnum'};
3640 return ( 'error' => "Can't resume session" ); #better error message
3643 ($context, $session, $custnum);