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 return { 'error' => '',
665 'custnum' => $custnum,
670 sub billing_history {
673 my($context, $session, $custnum) = _custoragent_session_custnum($p);
674 return { 'error' => $session } if $context eq 'error';
676 return { 'error' => 'No customer' } unless $custnum;
678 my $search = { 'custnum' => $custnum };
679 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
680 my $cust_main = qsearchs('cust_main', $search )
681 or return { 'error' => "unknown custnum $custnum" };
685 if ( $session->{'pkgnum'} ) {
686 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
687 #next_bill_date from cust_pkg?
688 return { 'error' => 'No history for package' };
691 $return{balance} = $cust_main->balance;
692 $return{balance_pretty} = money_pretty($return{balance});
693 $return{next_bill_date} = $cust_main->next_bill_date;
694 $return{next_bill_date_pretty} =
695 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
698 my $conf = new FS::Conf;
700 $return{'history'} = [
701 $cust_main->payment_history(
702 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
707 $return{'money_char'} = $conf->config("money_char") || '$',
715 my $session = _cache->get($p->{'session_id'})
716 or return { 'error' => "Can't resume session" }; #better error message
718 my $custnum = $session->{'custnum'}
719 or return { 'error' => "no customer record" };
721 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
722 or return { 'error' => "unknown custnum $custnum" };
724 my $new = new FS::cust_main { $cust_main->hash };
726 $new->set( $_ => $p->{$_} )
727 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
729 if ( exists($p->{address1}) ) {
730 my $bill_location = FS::cust_location->new({
731 map { $_ => $p->{$_} } @location_editable_fields
733 # if this is unchanged from before, cust_main::replace will ignore it
734 $new->set('bill_location' => $bill_location);
737 if ( exists($p->{ship_address1}) ) {
738 my $ship_location = FS::cust_location->new({
739 map { $_ => $p->{"ship_$_"} } @location_editable_fields
741 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
742 # Selfservice unfortunately tries to indicate "same as billing
743 # address" by sending all fields empty. Did this ever work?
744 $ship_location = $cust_main->bill_location;
746 $new->set('ship_location' => $ship_location);
748 # but if it hasn't been passed in at all, leave ship_location alone--
749 # DON'T change it to match bill_location.
751 my $conf = new FS::Conf;
754 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
755 #false laziness with httemplate/edit/process/cust_main.cgi
756 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
757 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
759 @invoicing_list = $cust_main->invoicing_list;
762 my $error = $new->replace($cust_main, \@invoicing_list);
763 return { 'error' => $error } if $error;
766 return { 'error' => '' };
771 my $session = _cache->get($p->{'session_id'})
772 or return { 'error' => "Can't resume session" }; #better error message
778 my $conf = new FS::Conf;
779 use vars qw($payment_info); #cache for performance
780 unless ( $payment_info ) {
782 my %states = map { $_->state => 1 }
783 qsearch('cust_main_county', {
784 'country' => $conf->config('countrydefault') || 'US'
787 my %cust_paybys = map { $_ => 1 }
788 map { FS::payby->payby2payment($_) }
789 $conf->config('signup_server-payby');
791 my @cust_paybys = keys %cust_paybys;
795 #list all counties/states/countries
796 'cust_main_county' =>
797 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
799 #shortcut for one-country folks
801 [ sort { $a cmp $b } keys %states ],
803 'card_types' => card_types(),
805 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
806 'require_cvv' => $conf->exists('selfservice-require_cvv'),
807 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
809 'paytypes' => [ FS::cust_payby::paytypes ],
811 'paybys' => [ $conf->config('signup_server-payby') ],
812 'cust_paybys' => \@cust_paybys,
814 'stateid_label' => FS::Msgcat::_gettext('stateid'),
815 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
817 'show_ss' => $conf->exists('show_ss'),
818 'show_stateid' => $conf->exists('show_stateid'),
819 'show_paystate' => $conf->exists('show_bankstate'),
821 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
823 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
832 my %return = %$payment_info;
834 my $custnum = $session->{'custnum'};
836 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
837 or return { 'error' => "unknown custnum $custnum" };
839 $return{'hide_payment_fields'} = [
841 my $pg = payment_gateway($cust_main, $_);
842 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
843 } @{ $return{cust_paybys} }
846 $return{balance} = $cust_main->balance; #XXX pkg-balances?
848 $return{$_} = $cust_main->bill_location->get($_)
849 for qw(address1 address2 city state zip);
851 #XXX look for stored cust_payby info
853 # $return{payname} = $cust_main->payname
854 # || ( $cust_main->first. ' '. $cust_main->get('last') );
856 #if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
857 # $return{card_type} = cardtype($cust_main->payinfo);
858 # $return{payinfo} = $cust_main->paymask;
860 # @return{'month', 'year'} = $cust_main->paydate_monthyear;
864 #if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
865 # my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
866 # $return{payinfo1} = $payinfo1;
867 # $return{payinfo2} = $payinfo2;
868 # $return{paytype} = $cust_main->paytype;
869 # $return{paystate} = $cust_main->paystate;
870 # $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
873 if ( $conf->config('prepayment_discounts-credit_type') ) {
875 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
878 #doubleclick protection
880 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
881 $return{paybatch} = $return{payunique}; #back compat
883 return { 'error' => '',
889 #some false laziness with httemplate/process/payment.cgi - look there for
890 #ACH and CVV support stuff
892 sub validate_payment {
895 my $session = _cache->get($p->{'session_id'})
896 or return { 'error' => "Can't resume session" }; #better error message
898 my $custnum = $session->{'custnum'};
900 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
901 or return { 'error' => "unknown custnum $custnum" };
903 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
904 or return { 'error' => gettext('illegal_amount') };
906 return { error => 'Amount must be greater than 0' } unless $amount > 0;
908 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
909 #changing the hidden form values
910 my $conf = new FS::Conf;
911 my $fee_display = $conf->config('selfservice_process-display') || 'add';
912 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
913 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
914 if ( $fee_display eq 'add'
916 and ! $fee_skip_first || scalar($cust_main->cust_pay)
919 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
920 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
923 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
924 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
925 my $discount_term = $1;
927 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
928 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
931 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
932 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
935 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
936 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
939 $payunique = $paybatch if ! length($payunique) && length($paybatch);
941 $p->{'payby'} ||= 'CARD';
942 $p->{'payby'} =~ /^([A-Z]{4})$/
943 or return { 'error' => "illegal_payby " . $p->{'payby'} };
946 #false laziness w/process/payment.cgi
949 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
951 $p->{'payinfo1'} =~ /^([\dx]+)$/
952 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
954 $p->{'payinfo2'} =~ /^([\dx]+)$/
955 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
957 $payinfo = $payinfo1. '@'. $payinfo2;
959 $payinfo = $cust_main->payinfo
960 if $cust_main->paymask eq $payinfo;
962 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
964 $payinfo = $p->{'payinfo'};
968 #more intelligent matching will be needed here if you change
969 #card_masking_method and don't remove existing paymasks
970 if ( $cust_main->paymask eq $payinfo ) {
971 $payinfo = $cust_main->payinfo;
976 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
977 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
981 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
982 return { 'error' => gettext('unknown_card_type') }
983 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
985 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
986 if ( cardtype($payinfo) eq 'American Express card' ) {
987 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
988 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
991 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
992 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
995 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
996 return { 'error' => 'CVV2 is required' };
997 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
998 return { 'error' => 'CVV2 is required' };
1002 die "unknown payby $payby";
1005 my %payby2fields = (
1006 'CARD' => [ qw( paystart_month paystart_year payissue payip
1007 address1 address2 city state zip country ) ],
1008 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1012 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1015 'cust_main' => $cust_main, #XXX or just custnum??
1016 'amount' => sprintf('%.2f', $amount),
1018 'payinfo' => $payinfo,
1019 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1020 'card_type' => $card_type,
1021 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1022 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1023 'month' => $p->{'month'},
1024 'year' => $p->{'year'},
1025 'payname' => $payname,
1026 'payunique' => $payunique,
1027 'paybatch' => $paybatch,
1028 'paycvv' => $paycvv,
1029 'payname' => $payname,
1030 'discount_term' => $discount_term,
1031 'pkgnum' => $session->{'pkgnum'},
1032 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1042 my $validate = validate_payment($p);
1043 return $validate if $validate->{'error'};
1045 my $conf = new FS::Conf;
1046 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1047 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1049 +{ map { $_=>$validate->{$_} }
1050 qw( card_type paymask payname paydate_pretty month year amount
1051 address1 address2 city state zip country
1057 sub process_stored_payment {
1060 my $session_id = $p->{'session_id'};
1062 my $payment_info = _cache->get( "payment_$session_id" )
1063 or return { 'error' => "Can't resume session" }; #better error message
1065 do_process_payment($payment_info);
1069 sub process_payment {
1072 my $payment_info = validate_payment($p);
1073 return $payment_info if $payment_info->{'error'};
1075 do_process_payment($payment_info);
1079 sub do_process_payment {
1080 my $validate = shift;
1082 my $cust_main = $validate->{'cust_main'};
1084 my $amount = delete $validate->{'amount'};
1087 my $payby = delete $validate->{'payby'};
1089 if ( $validate->{'save'} ) {
1090 my $new = new FS::cust_main { $cust_main->hash };
1091 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1092 $new->set( $_ => $validate->{$_} )
1093 foreach qw( payname paystart_month paystart_year payissue payip );
1094 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1096 my $bill_location = FS::cust_location->new({
1097 map { $_ => $validate->{$_} }
1098 qw(address1 address2 city state country zip)
1100 $new->set('bill_location' => $bill_location);
1101 # but don't allow the service address to change this way.
1103 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1104 $new->set( $_ => $validate->{$_} )
1105 foreach qw( payname payip paytype paystate
1106 stateid stateid_state );
1107 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1109 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1110 $new->set( 'paydate' => $validate->{'paydate'} );
1111 my $error = $new->replace($cust_main);
1113 #no, this causes customers to process their payments again
1114 #return { 'error' => $error };
1115 #XXX just warn verosely for now so i can figure out how these happen in
1116 # the first place, eventually should redirect them to the "change
1117 #address" page but indicate if the payment processed?
1118 delete($validate->{'payinfo'}); #don't want to log this!
1119 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1120 "NEW: ". Dumper($new)."\n".
1121 "OLD: ". Dumper($cust_main)."\n".
1122 "PACKET: ". Dumper($validate)."\n";
1128 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1132 'paynum_ref' => \$paynum,
1135 return { 'error' => $error } if $error;
1137 #no error, so order the fee package if applicable...
1138 my $conf = new FS::Conf;
1139 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1140 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1142 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1144 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1146 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1147 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1150 #and generate an invoice for it now too
1151 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1152 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1157 $cust_main->apply_payments;
1160 my $receipt_html = '';
1162 # currently supported for realtime CC only; send receipt data to SS
1163 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1166 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1169 <TD ALIGN="right">Payment#</TD>
1170 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1174 <TD ALIGN="right">Date</TD>
1176 <TD BGCOLOR="#FFFFFF"><B>! .
1177 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1183 <TD ALIGN="right">Amount</TD>
1184 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1189 <TD ALIGN="right">Payment method</TD>
1190 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1203 'amount' => sprintf('%.2f', $cust_pay->paid),
1204 'date' => $cust_pay->_date,
1205 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1206 'time_pretty' => time2str('%T', $cust_pay->_date),
1207 'auth_num' => $cust_pay->auth,
1208 'order_num' => $cust_pay->order_number,
1209 'receipt_html' => $receipt_html,
1216 'receipt_html' => '',
1223 sub realtime_collect {
1226 my $session = _cache->get($p->{'session_id'})
1227 or return { 'error' => "Can't resume session" }; #better error message
1229 my $custnum = $session->{'custnum'};
1231 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1232 or return { 'error' => "unknown custnum $custnum" };
1235 if ( $p->{'amount'} ) {
1236 $amount = $p->{'amount'};
1238 elsif ( $session->{'pkgnum'} ) {
1239 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1242 $amount = $cust_main->balance;
1245 my $error = $cust_main->realtime_collect(
1246 'method' => $p->{'method'},
1247 'amount' => $amount,
1248 'pkgnum' => $session->{'pkgnum'},
1249 'session_id' => $p->{'session_id'},
1253 return { 'error' => $error } unless ref( $error );
1255 return { 'error' => '', amount => $amount, %$error };
1258 sub start_thirdparty {
1260 my $session = _cache->get($p->{'session_id'})
1261 or return { 'error' => "Can't resume session" }; #better error message
1262 my $custnum = $session->{'custnum'};
1263 my $cust_main = FS::cust_main->by_key($custnum);
1265 my $amount = $p->{'amount'}
1266 or return { error => 'no amount' };
1268 my $result = $cust_main->create_payment(
1269 'method' => $p->{'method'},
1270 'amount' => $p->{'amount'},
1271 'pkgnum' => $session->{'pkgnum'},
1272 'session_id' => $p->{'session_id'},
1275 if ( ref($result) ) { # hashref or error
1278 return { error => $result };
1282 sub finish_thirdparty {
1284 my $session_id = delete $p->{'session_id'};
1285 my $session = _cache->get($session_id)
1286 or return { 'error' => "Can't resume session" };
1287 my $custnum = $session->{'custnum'};
1288 my $cust_main = FS::cust_main->by_key($custnum);
1290 if ( $p->{_cancel} ) {
1291 # customer backed out of making a payment
1292 return $cust_main->cancel_payment( $session_id );
1294 my $result = $cust_main->execute_payment( $session_id, %$p );
1295 if ( ref($result) ) {
1298 return { error => $result };
1302 sub process_payment_order_pkg {
1305 my $hr = process_payment($p);
1306 return $hr if $hr->{'error'};
1311 sub process_payment_order_renew {
1314 my $hr = process_payment($p);
1315 return $hr if $hr->{'error'};
1320 sub process_prepay {
1324 my $session = _cache->get($p->{'session_id'})
1325 or return { 'error' => "Can't resume session" }; #better error message
1329 my $custnum = $session->{'custnum'};
1331 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1332 or return { 'error' => "unknown custnum $custnum" };
1334 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1335 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1343 return { 'error' => $error } if $error;
1345 return { 'error' => '',
1346 'amount' => $amount,
1347 'seconds' => $seconds,
1348 'duration' => duration_exact($seconds),
1349 'upbytes' => $upbytes,
1350 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1351 'downbytes' => $downbytes,
1352 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1353 'totalbytes'=> $totalbytes,
1354 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1361 my $session = _cache->get($p->{'session_id'})
1362 or return { 'error' => "Can't resume session" }; #better error message
1364 my $custnum = $session->{'custnum'};
1366 my $invnum = $p->{'invnum'};
1368 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1369 'custnum' => $custnum } )
1370 or return { 'error' => "Can't find invnum" };
1374 return { 'error' => '',
1375 'invnum' => $invnum,
1376 'invoice_text' => join('', $cust_bill->print_text ),
1377 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1384 my $session = _cache->get($p->{'session_id'})
1385 or return { 'error' => "Can't resume session" }; #better error message
1387 my $custnum = $session->{'custnum'};
1389 my $invnum = $p->{'invnum'};
1391 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1392 'custnum' => $custnum } )
1393 or return { 'error' => "Can't find invnum" };
1397 return { 'error' => '',
1398 'invnum' => $invnum,
1399 'invoice_pdf' => $cust_bill->print_pdf({
1400 'unsquelch_cdr' => 1,
1401 'locale' => $p->{'locale'},
1407 sub legacy_invoice {
1409 my $session = _cache->get($p->{'session_id'})
1410 or return { 'error' => "Can't resume session" }; #better error message
1412 my $custnum = $session->{'custnum'};
1414 my $legacyinvnum = $p->{'legacyinvnum'};
1417 'legacyinvnum' => $legacyinvnum,
1418 'custnum' => $custnum,
1421 my $legacy_cust_bill =
1422 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1423 || qsearchs('legacy_cust_bill', \%hash )
1424 or return { 'error' => "Can't find legacyinvnum" };
1428 return { 'error' => '',
1429 'legacyinvnum' => $legacyinvnum,
1430 'legacyid' => $legacy_cust_bill->legacyid,
1431 'invoice_html' => $legacy_cust_bill->content_html,
1436 sub legacy_invoice_pdf {
1438 my $session = _cache->get($p->{'session_id'})
1439 or return { 'error' => "Can't resume session" }; #better error message
1441 my $custnum = $session->{'custnum'};
1443 my $legacyinvnum = $p->{'legacyinvnum'};
1445 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1446 'legacyinvnum' => $legacyinvnum,
1447 'custnum' => $custnum,
1448 }) or return { 'error' => "Can't find legacyinvnum" };
1452 return { 'error' => '',
1453 'legacyinvnum' => $legacyinvnum,
1454 'legacyid' => $legacy_cust_bill->legacyid,
1455 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1463 #sessioning for this? how do we get the session id to the backend invoice
1464 # template so it can add it to the link, blah
1467 if ( $p->{'invnum'} ) {
1468 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1469 or return { 'error' => 'unknown invnum' };
1470 $agentnum = $cust_bill->cust_main->agentnum;
1473 my $templatename = $p->{'template'} || $p->{'templatename'};
1475 #false laziness-ish w/view/cust_bill-logo.cgi
1477 my $conf = new FS::Conf;
1478 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1479 $templatename = "_$1";
1484 my $filename = "logo$templatename.png";
1486 return { 'error' => '',
1487 'logo' => $conf->config_binary($filename, $agentnum),
1488 'content_type' => 'image/png', #should allow gif, jpg too
1494 my $session = _cache->get($p->{'session_id'})
1495 or return { 'error' => "Can't resume session" }; #better error message
1497 my $custnum = $session->{'custnum'};
1499 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1500 or return { 'error' => "unknown custnum $custnum" };
1502 my $conf = new FS::Conf;
1504 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1506 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1511 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1512 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1513 my $owed = $_->owed;
1515 +{ 'invnum' => $_->invnum,
1516 '_date' => $_->_date,
1517 'date' => time2str("%b %o, %Y", $_->_date),
1518 'date_short' => time2str("%m-%d-%Y", $_->_date),
1519 'previous' => sprintf('%.2f', ($_->previous)[0]),
1520 'charged' => sprintf('%.2f', $_->charged),
1521 'owed' => sprintf('%.2f', $owed),
1522 'balance' => sprintf('%.2f', $balance),
1523 'lastpay' => @payments_and_credits
1524 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1530 return { 'error' => '',
1531 'balance' => $cust_main->balance,
1532 'money_char' => $conf->config("money_char") || '$',
1533 'invoices' => $invoices,
1534 'legacy_invoices' => [
1536 +{ 'legacyinvnum' => $_->legacyinvnum,
1537 'legacyid' => $_->legacyid,
1538 '_date' => $_->_date,
1539 'date' => time2str("%b %o, %Y", $_->_date),
1540 'date_short' => time2str("%m-%d-%Y", $_->_date),
1541 'charged' => sprintf('%.2f', $_->charged),
1542 'has_content' => ( length($_->content_pdf)
1543 || length($_->content_html) ),
1554 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1555 return { 'error' => $session } if $context eq 'error';
1557 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1558 or return { 'error' => "unknown custnum $custnum" };
1562 my $cust_payby = $_;
1564 map { $_ => $cust_payby->$_ }
1565 qw( custpaybynum weight payby paymask paydate
1566 payname paystate paytype
1570 $cust_main->cust_payby
1578 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1579 return { 'error' => $session } if $context eq 'error';
1581 #XXX payinfo1 + payinfo2 for CHEK?
1582 #or take the opportunity to use separate, more well- named fields?
1584 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1585 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1586 # my $payinfo1 = $1;
1587 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1588 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1589 # my $payinfo2 = $1;
1590 # $payinfo = $payinfo1. '@'. $payinfo2;
1592 my $cust_payby = new FS::cust_payby {
1593 'custnum' => $custnum,
1594 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1595 paystate paytype payip
1599 my $error = $cust_payby->insert;
1601 return { 'error' => $error };
1603 return { 'custpaybynum' => $cust_payby->custpaybynum };
1611 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1612 return { 'error' => $session } if $context eq 'error';
1614 my $cust_payby = qsearchs('cust_payby', {
1615 'custnum' => $custnum,
1616 'custpaybynum' => $p->{'custpaybynum'},
1618 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1620 return { 'error' => $cust_payby->delete };
1626 my $session = _cache->get($p->{'session_id'})
1627 or return { 'error' => "Can't resume session" }; #better error message
1629 my $custnum = $session->{'custnum'};
1631 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1632 or return { 'error' => "unknown custnum $custnum" };
1634 my @errors = $cust_main->cancel( 'quiet'=>1 );
1636 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1638 return { 'error' => $error };
1645 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1646 return { 'error' => $session } if $context eq 'error';
1648 my $search = { 'custnum' => $custnum };
1649 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1650 my $cust_main = qsearchs('cust_main', $search )
1651 or return { 'error' => "unknown custnum $custnum" };
1653 my $conf = new FS::Conf;
1654 my $immutable = $conf->exists('selfservice_immutable-package');
1656 # the duplication below is necessary:
1657 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1658 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1659 # non-backwards-compatible change breaking the software of anyone using the API
1660 # instead of the stock selfservice
1661 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1662 if( $conf->exists('selfservice_server-view-wholesale') ) {
1663 return { 'svcnum' => $session->{'svcnum'},
1664 'custnum' => $custnum,
1665 'cust_pkg' => [ map {
1667 immutable => $immutable,
1668 part_pkg => [ map $_->hashref, $_->part_pkg ],
1670 [ map $_->hashref, $_->available_part_svc ],
1672 [ map { my $ref = { $_->hash,
1673 label => [ $_->label ],
1675 $ref->{_password} = $_->svc_x->_password
1676 if $context eq 'agent'
1677 && $conf->exists('agent-showpasswords')
1678 && $_->part_svc->svcdb eq 'svc_acct';
1683 } $cust_main->cust_pkg
1686 small_custview( $cust_main, $conf->config('countrydefault') ),
1687 'wholesale_view' => 1,
1688 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1689 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1690 'lnp' => $conf->exists('svc_phone-lnp'),
1694 { 'svcnum' => $session->{'svcnum'},
1695 'custnum' => $custnum,
1696 'cust_pkg' => [ map {
1697 my $primary_cust_svc = $_->primary_cust_svc;
1700 immutable => $immutable,
1701 pkg_label => $_->pkg_locale,
1702 status => $_->status,
1703 statuscolor => $_->statuscolor,
1705 [ map { $_->hashref }
1706 grep { $_->selfservice_access ne 'hidden' }
1707 $_->available_part_svc
1710 [ map { my $ref = { $_->hash,
1711 label => [ $_->label ],
1713 $ref->{_password} = $_->svc_x->_password
1714 if $context eq 'agent'
1715 && $conf->exists('agent-showpasswords')
1716 && $_->part_svc->svcdb eq 'svc_acct';
1717 $ref->{svchash} = { $_->svc_x->hash } if
1718 $_->part_svc->svcdb eq 'svc_phone';
1719 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1720 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1723 grep { $_->part_svc->selfservice_access ne 'hidden' }
1728 ? { $primary_cust_svc->hash,
1729 label => [ $primary_cust_svc->label ],
1730 finger => $primary_cust_svc->svc_x->finger, #uuh
1731 $primary_cust_svc->part_svc->hash,
1735 } $cust_main->ncancelled_pkgs
1738 small_custview( $cust_main, $conf->config('countrydefault') ),
1739 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1747 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1748 return { 'error' => $session } if $context eq 'error';
1750 my $conf = new FS::Conf;
1752 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1753 my $search = { 'custnum' => $custnum };
1754 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1755 my $cust_main = qsearchs('cust_main', $search )
1756 or return { 'error' => "unknown custnum $custnum" };
1758 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1759 if ( ! $pkgnum && $p->{'svcnum'} ) {
1760 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1761 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1765 my @cust_pkg_usage = ();
1766 foreach my $cust_pkg ( $p->{'ncancelled'}
1767 ? $cust_main->ncancelled_pkgs
1768 : $cust_main->unsuspended_pkgs ) {
1769 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1770 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1771 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1774 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1777 foreach (@cust_pkg_usage) {
1778 my $part = $_->part_pkg_usage;
1779 my $tag = $part->description . ($part->shared ? 1 : 0);
1780 my $row = $usage_pools{$tag}
1781 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1782 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1783 $row->[2] += $part->minutes; # minutes total
1785 } # otherwise just leave them empty
1787 if ( $p->{'svcdb'} ) {
1788 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1790 : ref($p->{'svcdb'}) eq 'ARRAY'
1791 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1792 : { $p->{'svcdb'} => 1 };
1793 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1796 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1799 my @svcs; # stuff to return to the client
1800 foreach my $cust_svc (@cust_svc) {
1801 my $svc_x = $cust_svc->svc_x;
1802 my($label, $value) = $cust_svc->label;
1803 my $part_svc = $cust_svc->part_svc;
1804 my $svcdb = $part_svc->svcdb;
1805 my $cust_pkg = $cust_svc->cust_pkg;
1806 my $part_pkg = $cust_pkg->part_pkg;
1809 'svcnum' => $cust_svc->svcnum,
1810 'display_svcnum' => $cust_svc->display_svcnum,
1814 'pkg_label' => $cust_pkg->pkg_locale,
1815 'pkg_status' => $cust_pkg->status,
1816 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1819 # would it make sense to put this in a svc_* method?
1821 if ( $svcdb eq 'svc_acct' ) {
1822 foreach (qw(username email finger seconds)) {
1823 $hash{$_} = $svc_x->$_;
1829 'upbytes' => display_bytecount($svc_x->upbytes),
1830 'downbytes' => display_bytecount($svc_x->downbytes),
1831 'totalbytes' => display_bytecount($svc_x->totalbytes),
1833 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1834 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1835 'recharge_upbytes' =>
1836 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1837 'recharge_downbytes' =>
1838 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1839 'recharge_totalbytes' =>
1840 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1845 } elsif ( $svcdb eq 'svc_dsl' ) {
1847 $hash{'phonenum'} = $svc_x->phonenum;
1848 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1849 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1850 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1853 $hash{'name'} = $cust_main->name;
1855 # no usage to hide here
1857 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1859 # could potentially show lots of things...
1860 $hash{'outbound'} = 1;
1861 $hash{'inbound'} = 0;
1862 if ( $svcdb eq 'svc_phone' ) {
1863 if ( $part_pkg->plan eq 'voip_inbound' ) {
1864 $hash{'outbound'} = 0;
1865 $hash{'inbound'} = 1;
1866 } elsif ( $part_pkg->option('selfservice_inbound_format')
1867 or $conf->config('selfservice-default_inbound_cdr_format')
1869 $hash{'inbound'} = 1;
1872 foreach (qw(inbound outbound)) {
1873 # hmm...we can't filter by status here, because there might
1874 # not be cdr_terminations at all. have to go by date.
1875 # find all since the last bill date.
1876 # XXX cdr types? we are going to need them.
1878 my $sum_cdr = $svc_x->sum_cdrs(
1879 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1880 'begin' => ($cust_pkg->last_bill || 0),
1882 'disable_charged_party' => 1,
1884 $hash{$_} = $sum_cdr->hashref;
1887 } # not hiding usage
1891 } # foreach $cust_svc
1894 'svcnum' => $session->{'svcnum'},
1895 'custnum' => $custnum,
1896 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1897 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1900 map { $usage_pools{$_} }
1904 'hide_usage' => $hide_usage,
1909 sub _customer_svc_x {
1910 my($custnum, $svcnum, $table) = (shift, shift, shift);
1911 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1913 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1914 my $search = " AND custnum = $1";
1915 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1918 'table' => ($table || 'svc_acct'),
1919 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1920 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1921 #'LEFT JOIN cust_main USING ( custnum ) ',
1922 'hashref' => $hashref,
1923 'extra_sql' => $search, #important
1928 sub svc_status_html {
1931 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1932 return { 'error' => $session } if $context eq 'error';
1934 #XXX only svc_dsl for now
1935 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1936 or return { 'error' => "Service not found" };
1938 my $html = $svc_x->getstatus_html;
1940 return { 'html' => $html };
1944 sub svc_status_hash {
1947 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1948 return { 'error' => $session } if $context eq 'error';
1950 #XXX only svc_acct for now
1951 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1952 or return { 'error' => "Service not found" };
1954 my ( $html, $hashref ) = $svc_x->export_getstatus;
1959 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1960 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1961 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1962 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1963 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1966 my( $p, $method ) = @_;
1968 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1969 return { 'error' => $session } if $context eq 'error';
1971 #XXX only svc_acct for now
1972 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1973 or return { 'error' => "Service not found" };
1975 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1977 my $error = $svc_x->$method($p); #$p? returns error?
1978 return { 'error' => $error } if $error;
1980 return {}; #? { 'error' => '' }
1984 sub acct_forward_info {
1987 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1988 return { 'error' => $session } if $context eq 'error';
1990 my $svc_forward = _customer_svc_x( $custnum,
1991 { 'srcsvc' => $p->{'svcnum'} },
1994 or return { 'error' => '',
1998 return { 'error' => '',
1999 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2004 sub process_acct_forward {
2006 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2007 return { 'error' => $session } if $context eq 'error';
2009 my $old = _customer_svc_x( $custnum,
2010 { 'srcsvc' => $p->{'svcnum'} },
2014 if ( $p->{'dst'} eq '' ) {
2016 my $error = $old->delete;
2017 return { 'error' => $error };
2019 return { 'error' => '' };
2022 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2023 'dst' => $p->{'dst'},
2028 $new->svcnum($old->svcnum);
2029 my $cust_svc = $old->cust_svc;
2030 $new->svcpart($old->svcpart);
2031 $new->pkgnuym($old->pkgnum);
2032 $error = $new->replace($old);
2034 my $conf = new FS::Conf;
2035 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2037 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2038 or return { 'error' => 'No service' }; #how would we even get here?
2040 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2042 $error = $new->insert;
2045 return { 'error' => $error };
2049 sub list_dsl_devices {
2052 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2053 return { 'error' => $session } if $context eq 'error';
2055 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2056 or return { 'error' => "Service not found" };
2059 'devices' => [ map {
2060 +{ 'mac_addr' => $_->mac_addr };
2061 } $svc_dsl->dsl_device
2067 sub add_dsl_device {
2070 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2071 return { 'error' => $session } if $context eq 'error';
2073 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2074 or return { 'error' => "Service not found" };
2076 return { 'error' => 'No MAC address supplied' }
2077 unless length($p->{'mac_addr'});
2079 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2080 'mac_addr' => scalar($p->{'mac_addr'}),
2082 my $error = $dsl_device->insert;
2083 return { 'error' => $error };
2087 sub delete_dsl_device {
2090 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2091 return { 'error' => $session } if $context eq 'error';
2093 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2094 or return { 'error' => "Service not found" };
2096 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2097 'mac_addr' => scalar($p->{'mac_addr'}),
2100 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2102 my $error = $dsl_device->delete;
2103 return { 'error' => $error };
2109 _usage_details( \&_port_graph, $p,
2110 'svcdb' => 'svc_port',
2115 my($svc_port, $begin, $end) = @_;
2117 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2118 push @usage, { 'png' => $pngOrError };
2122 sub _list_svc_usage {
2123 my($svc_acct, $begin, $end) = @_;
2125 foreach my $part_export (
2126 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2127 qw( sqlradius sqlradius_withdomain )
2129 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2134 sub list_svc_usage {
2135 _usage_details(\&_list_svc_usage, @_);
2138 sub _list_support_usage {
2139 my($svc_acct, $begin, $end) = @_;
2141 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2142 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2144 push @usage, { 'seconds' => $_->seconds,
2145 'support' => $_->support,
2146 '_date' => $_->_date,
2147 'id' => $_->transaction_id,
2148 'creator' => $_->creator,
2149 'subject' => $_->subject,
2150 'status' => $_->status,
2151 'ticketid' => $_->ticketid,
2157 sub list_support_usage {
2158 _usage_details(\&_list_support_usage, @_);
2161 sub _list_cdr_usage {
2162 # XXX CDR type support...
2163 # XXX any way to do a paged search on this?
2164 # we have to return the results all at once...
2165 my($svc_x, $begin, $end, %opt) = @_;
2166 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2170 'disable_charged_party' => 1,
2175 sub list_cdr_usage {
2177 _usage_details( \&_list_cdr_usage, $p );
2180 sub _usage_details {
2181 my($callback, $p, %opt) = @_;
2182 my $conf = FS::Conf->new;
2184 if ( $conf->exists('selfservice_hide-usage') ) {
2185 return { 'error' => 'Viewing usage is not allowed.' };
2188 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2189 return { 'error' => $session } if $context eq 'error';
2191 my $search = { 'svcnum' => $p->{'svcnum'} };
2192 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2194 my $cust_svc = qsearchs( 'cust_svc', $search );
2195 return { 'error' => 'No service selected in list_svc_usage' }
2198 my $svc_x = $cust_svc->svc_x;
2199 my $svcdb = $svc_x->table;
2200 my $cust_pkg = $cust_svc->cust_pkg;
2201 my $freq = $cust_pkg->part_pkg->freq;
2204 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2206 if ( $p->{inbound} ) {
2207 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2208 || $conf->config('selfservice-default_inbound_cdr_format')
2209 || 'source_default';
2210 $callback_opt{inbound} = 1;
2212 $format = $cust_pkg->part_pkg->option('selfservice_format')
2213 || $conf->config('selfservice-default_cdr_format')
2217 $callback_opt{format} = $format;
2218 $callback_opt{use_clid} = 1;
2219 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2222 my $start = $cust_pkg->setup;
2223 #my $end = $cust_pkg->bill; # or time?
2226 unless ( $p->{beginning} ) {
2227 $p->{beginning} = $cust_pkg->last_bill;
2228 $p->{ending} = $end;
2231 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2232 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2234 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2238 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2239 # ugly kludge, I know
2240 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2241 if (defined $delete_col) {
2242 delete($_->[$delete_col]) foreach ($header, @usage);
2246 #kinda false laziness with FS::cust_main::bill, but perhaps
2247 #we should really change this bit to DateTime and DateTime::Duration
2249 #change this bit to use Date::Manip? CAREFUL with timezones (see
2250 # mailing list archive)
2251 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2252 (localtime($p->{ending}) )[0,1,2,3,4,5];
2253 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2254 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2256 if ( $freq =~ /^\d+$/ ) {
2258 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2260 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2261 } elsif ( $freq =~ /^(\d+)w$/ ) {
2263 $nmday += $weeks * 7;
2264 $pmday -= $weeks * 7;
2265 } elsif ( $freq =~ /^(\d+)d$/ ) {
2269 } elsif ( $freq =~ /^(\d+)h$/ ) {
2274 return { 'error' => "unparsable frequency: ". $freq };
2277 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2278 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2282 'svcnum' => $p->{svcnum},
2283 'beginning' => $p->{beginning},
2284 'ending' => $p->{ending},
2285 'inbound' => $p->{inbound},
2286 'previous' => ($previous > $start) ? $previous : $start,
2287 'next' => ($next < $end) ? $next : $end,
2288 'header' => $header,
2296 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2297 return { 'error' => $session } if $context eq 'error';
2299 my $search = { 'custnum' => $custnum };
2300 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2301 my $cust_main = qsearchs('cust_main', $search )
2302 or return { 'error' => "unknown custnum $custnum" };
2304 my $status = $cust_main->status;
2306 my %order_pkg_options = ();
2307 if ( $p->{locationnum} > 0 ) {
2308 $order_pkg_options{locationnum} = delete($p->{locationnum});
2309 } elsif ( $p->{address1} ) {
2310 $order_pkg_options{'cust_location'} = new FS::cust_location {
2311 map { $_ => $p->{$_} }
2312 qw( address1 address2 city county state zip country )
2316 #false laziness w/ClientAPI/Signup.pm
2318 my $cust_pkg = new FS::cust_pkg ( {
2319 'custnum' => $custnum,
2320 'pkgpart' => $p->{'pkgpart'},
2321 'quantity' => $p->{'quantity'} || 1,
2323 my $error = $cust_pkg->check;
2324 return { 'error' => $error } if $error;
2327 unless ( $p->{'svcpart'} eq 'none' ) {
2331 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2333 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2334 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2335 $svcdb = $part_svc->svcdb;
2337 $svcdb = 'svc_acct';
2339 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2342 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2343 'svc_domain' => [ qw( domain ) ],
2344 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2345 'svc_external' => [ qw( id title ) ],
2346 'svc_pbx' => [ qw( id title ) ],
2349 my $svc_x = "FS::$svcdb"->new( {
2350 'svcpart' => $svcpart,
2351 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2354 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2357 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2358 my $acct_snarf = new FS::acct_snarf ( {
2359 'machine' => $p->{"snarf_machine$snarfnum"},
2360 'protocol' => $p->{"snarf_protocol$snarfnum"},
2361 'username' => $p->{"snarf_username$snarfnum"},
2362 '_password' => $p->{"snarf_password$snarfnum"},
2365 push @acct_snarf, $acct_snarf;
2367 $svc_x->child_objects( \@acct_snarf );
2370 my $y = $svc_x->setdefault; # arguably should be in new method
2371 return { 'error' => $y } if $y && !ref($y);
2373 $error = $svc_x->check;
2374 return { 'error' => $error } if $error;
2380 $error = $cust_main->order_pkg(
2381 'cust_pkg' => $cust_pkg,
2386 return { 'error' => $error } if $error;
2388 my $conf = new FS::Conf;
2389 if ( $conf->exists('signup_server-realtime') ) {
2391 my $bill_error = _do_bop_realtime( $cust_main, $status );
2394 $cust_pkg->cancel('quiet'=>1);
2397 $cust_pkg->reexport;
2401 $cust_pkg->reexport;
2404 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2406 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2413 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2414 return { 'error' => $session } if $context eq 'error';
2416 my $conf = new FS::Conf;
2417 my $immutable = $conf->exists('selfservice_immutable-package');
2418 return { 'error' => "Package modification disabled" } if $immutable;
2420 my $search = { 'custnum' => $custnum };
2421 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2422 my $cust_main = qsearchs('cust_main', $search )
2423 or return { 'error' => "unknown custnum $custnum" };
2425 my $status = $cust_main->status;
2426 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2427 or return { 'error' => "unknown package $p->{pkgnum}" };
2429 #if someone does need self-service package change of suspended packages,
2430 # figure out how to be more discriminating
2431 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2432 if $cust_pkg->status eq 'suspended';
2434 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2435 'quantity' => $p->{'quantity'} || 1,
2438 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2439 unless ref($err_or_cust_pkg);
2441 if ( $conf->exists('signup_server-realtime') ) {
2443 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2446 $err_or_cust_pkg->suspend;
2449 $err_or_cust_pkg->reexport;
2453 $err_or_cust_pkg->reexport;
2456 return { error => '', pkgnum => $cust_pkg->pkgnum };
2460 sub order_recharge {
2463 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2464 return { 'error' => $session } if $context eq 'error';
2466 my $search = { 'custnum' => $custnum };
2467 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2468 my $cust_main = qsearchs('cust_main', $search )
2469 or return { 'error' => "unknown custnum $custnum" };
2471 my $status = $cust_main->status;
2472 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2473 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2475 my $svc_x = $cust_svc->svc_x;
2476 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2479 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2480 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2481 recharge_totalbytes );
2482 my $amount = $part_pkg->option('recharge_amount', 1);
2484 my ($l, $v, $d) = $cust_svc->label; # blah
2485 my $pkg = "Recharge $v";
2487 my $bill_error = $cust_main->charge($amount, $pkg,
2488 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2489 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2490 $part_pkg->taxclass); #meh
2492 my $conf = new FS::Conf;
2493 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2495 $bill_error = _do_bop_realtime( $cust_main, $status );
2500 my $error = $svc_x->recharge (\%vhash);
2501 return { 'error' => $error } if $error;
2505 my $error = $bill_error;
2506 $error ||= $svc_x->recharge (\%vhash);
2507 return { 'error' => $error } if $error;
2510 return { error => '', svc => $cust_svc->part_svc->svc };
2514 sub _do_bop_realtime {
2515 my ($cust_main, $status, %opt) = @_;
2517 my $old_balance = $cust_main->balance;
2520 my $bill_error = $cust_main->bill(
2521 'return_bill' => \@cust_bill,
2524 $bill_error ||= $cust_main->apply_payments_and_credits;
2526 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2528 if ( $cust_main->balance > $old_balance
2529 && $cust_main->balance > 0
2530 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2533 unless ( $opt{'no_invoice_void'} ) {
2535 #this used to apply a credit, but now we can void invoices...
2536 foreach my $cust_bill (@cust_bill) {
2537 my $voiderror = $cust_bill->void('automatic payment failed');
2538 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2543 return { 'error' => '_decline', 'bill_error' => $bill_error };
2552 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2553 return { 'error' => $session } if $context eq 'error';
2555 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2556 or return { 'error' => "unknown custnum $custnum" };
2558 my @cust_pkg = sort { $a->bill <=> $b->bill }
2559 grep { $_->part_pkg->freq ne '0' }
2560 $cust_main->ncancelled_pkgs;
2562 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2564 my $total = $cust_main->balance;
2567 my $bill = $_->bill;
2568 $total += $_->part_pkg->base_recur($_, \$bill);
2569 my $renew_date = $_->part_pkg->add_freq($_->bill);
2571 'pkgnum' => $_->pkgnum,
2572 'amount' => sprintf('%.2f', $total),
2573 'bill_date' => $_->bill,
2574 'bill_date_pretty' => time2str('%x', $_->bill),
2575 'renew_date' => $renew_date,
2576 'renew_date_pretty' => time2str('%x', $renew_date),
2577 'expire_date' => $_->expire,
2578 'expire_date_pretty' => time2str('%x', $_->expire),
2583 return { 'dates' => \@array };
2587 sub payment_info_renew_info {
2589 my $renew_info = renew_info($p);
2590 my $payment_info = payment_info($p);
2591 return { %$renew_info,
2599 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2600 return { 'error' => $session } if $context eq 'error';
2602 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2603 or return { 'error' => "unknown custnum $custnum" };
2605 my $date = $p->{'date'};
2609 #freeside-daily -n -d $date fs_daily $custnum
2610 $cust_main->bill_and_collect( 'time' => $date,
2611 'invoice_time' => $now,
2612 'actual_time' => $now,
2613 'check_freq' => '1d',
2616 return { 'error' => '' };
2622 my $session = _cache->get($p->{'session_id'})
2623 or return { 'error' => "Can't resume session" }; #better error message
2625 my $custnum = $session->{'custnum'};
2627 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2628 or return { 'error' => "unknown custnum $custnum" };
2630 my $conf = new FS::Conf;
2632 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2633 or return { 'error' => 'Permission denied' };
2635 my $pkgnum = $p->{'pkgnum'};
2637 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2638 'pkgnum' => $pkgnum, } )
2639 or return { 'error' => "unknown pkgnum $pkgnum" };
2641 my $error = $cust_pkg->suspend(reason => $reasonnum);
2642 return { 'error' => $error };
2648 my $session = _cache->get($p->{'session_id'})
2649 or return { 'error' => "Can't resume session" }; #better error message
2651 my $custnum = $session->{'custnum'};
2653 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2654 or return { 'error' => "unknown custnum $custnum" };
2656 my $pkgnum = $p->{'pkgnum'};
2658 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2659 'pkgnum' => $pkgnum, } )
2660 or return { 'error' => "unknown pkgnum $pkgnum" };
2662 my $error = $cust_pkg->cancel('quiet' => 1);
2663 return { 'error' => $error };
2667 sub provision_phone {
2670 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2672 #editing an existing phone number
2673 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2674 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2675 return { 'error' => $session } if $context eq 'error';
2677 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2678 return { 'error' => 'service not found' } unless $svc_phone;
2679 return { 'error' => 'invalid svcnum' }
2680 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2682 $svc_phone->email($p->{'email'})
2683 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2684 $svc_phone->forwarddst($p->{'forwarddst'})
2685 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2686 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2687 return { 'error' => $svc_phone->replace };
2691 unless ( $p->{'lnp'} ) {
2692 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2693 $p->{'lnp_status'} = "portingin";
2694 return _provision( 'FS::svc_phone',
2695 [qw(lnp_desired_due_date lnp_other_provider
2696 lnp_other_provider_account phonenum countrycode lnp_status)],
2697 [qw(phonenum countrycode)],
2703 # single DID order (the usual case)
2704 unless (scalar(@bulkdid)) {
2705 return _provision( 'FS::svc_phone',
2706 [qw(phonenum countrycode)],
2707 [qw(phonenum countrycode)],
2713 # bulk DID order case
2715 foreach my $did ( @bulkdid ) {
2716 $did =~ s/[^0-9]//g;
2717 $error = _provision( 'FS::svc_phone',
2718 [qw(phonenum countrycode)],
2719 [qw(phonenum countrycode)],
2721 'pkgnum' => $p->{'pkgnum'},
2722 'svcpart' => $p->{'svcpart'},
2724 'countrycode' => $p->{'countrycode'},
2725 'session_id' => $p->{'session_id'},
2728 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2730 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2735 warn "provision_pbx called\n"
2738 warn "provision_pbx calling _provision\n"
2740 _provision( 'FS::svc_pbx',
2741 [qw(id title max_extensions max_simultaneous ip_addr)],
2742 [qw(id title max_extensions max_simultaneous ip_addr)],
2748 sub provision_acct {
2750 warn "provision_acct called\n"
2753 return { 'error' => gettext('passwords_dont_match') }
2754 if $p->{'_password'} ne $p->{'_password2'};
2755 return { 'error' => gettext('empty_password') }
2756 unless length($p->{'_password'});
2758 if ($p->{'domsvc'}) {
2759 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2760 qw ( svcpart pkgnum ) );
2761 return { 'error' => gettext('invalid_domain') }
2762 unless ($domains{$p->{'domsvc'}});
2765 warn "provision_acct calling _provision\n"
2767 _provision( 'FS::svc_acct',
2768 [qw(username _password domsvc)],
2769 [qw(username _password domsvc)],
2775 sub provision_external {
2777 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2778 _provision( 'FS::svc_external',
2786 sub provision_forward {
2788 _provision( 'FS::svc_forward',
2789 ['srcsvc','src','dstsvc','dst'],
2796 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2797 warn "_provision called for $class\n"
2800 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2801 return { 'error' => $session } if $context eq 'error';
2803 my $search = { 'custnum' => $custnum };
2804 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2805 my $cust_main = qsearchs('cust_main', $search )
2806 or return { 'error' => "unknown custnum $custnum" };
2808 my $pkgnum = $p->{'pkgnum'};
2810 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2812 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2813 'pkgnum' => $pkgnum,
2815 or return { 'error' => "unknown pkgnum $pkgnum" };
2817 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2819 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2820 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2822 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2823 if $class ne 'FS::'. $part_svc->svcdb;
2825 warn "creating $class record\n"
2827 my $svc_x = $class->new( {
2828 'pkgnum' => $p->{'pkgnum'},
2829 'svcpart' => $p->{'svcpart'},
2830 map { $_ => $p->{$_} } @$fields
2833 my %insert_args = ();
2834 #i shouldn't be a special case here (pass an option or something)
2835 if ( $class eq 'FS::svc_phone'
2836 && grep length($p->{$_}), @location_editable_fields
2839 $insert_args{'cust_location'} = new FS::cust_location {
2840 map { $_ => $p->{$_} } @location_editable_fields
2844 warn "inserting $class record\n"
2846 my $error = $svc_x->insert(%insert_args);
2849 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2851 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2854 my $return = { 'svc' => $part_svc->svc,
2856 map { $_ => $svc_x->get($_) } @$return_fields
2858 warn "_provision returning ". Dumper($return). "\n"
2867 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2868 return { 'error' => $session } if $context eq 'error';
2870 my $search = { 'custnum' => $custnum };
2871 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2872 my $cust_main = qsearchs('cust_main', $search )
2873 or return { 'error' => "unknown custnum $custnum" };
2875 my $pkgnum = $p->{'pkgnum'};
2877 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2878 'pkgnum' => $pkgnum,
2880 or return { 'error' => "unknown pkgnum $pkgnum" };
2882 my $svcpart = $p->{'svcpart'};
2884 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2885 'svcpart' => $svcpart, } )
2886 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2887 my $part_svc = $pkg_svc->part_svc;
2889 my $conf = new FS::Conf;
2892 'svc' => $part_svc->svc,
2893 'svcdb' => $part_svc->svcdb,
2894 'pkgnum' => $pkgnum,
2895 'svcpart' => $svcpart,
2896 'custnum' => $custnum,
2898 'security_phrase' => 0, #XXX !
2899 'svc_acct_pop' => [], #XXX !
2901 'init_popstate' => '',
2906 small_custview( $cust_main, $conf->config('countrydefault') ),
2910 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2911 && $ret->{'svcdb'} eq 'svc_phone') {
2912 $ret->{'svcnum'} = $p->{'svcnum'};
2913 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2914 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2915 $ret->{'email'} = $svc_phone->email;
2916 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2920 if ($ret->{'svcdb'} eq 'svc_forward') {
2921 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2927 sub unprovision_svc {
2930 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2931 return { 'error' => $session } if $context eq 'error';
2933 my $search = { 'custnum' => $custnum };
2934 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2935 my $cust_main = qsearchs('cust_main', $search )
2936 or return { 'error' => "unknown custnum $custnum" };
2938 my $svcnum = $p->{'svcnum'};
2940 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2941 or return { 'error' => "unknown svcnum $svcnum" };
2943 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2944 unless $cust_svc->cust_pkg->custnum == $custnum;
2946 my $conf = new FS::Conf;
2948 return { 'svc' => $cust_svc->part_svc->svc,
2949 'error' => $cust_svc->cancel,
2951 small_custview( $cust_main, $conf->config('countrydefault') ),
2956 sub myaccount_passwd {
2958 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2959 return { 'error' => $session } if $context eq 'error';
2961 return { 'error' => "New passwords don't match." }
2962 if $p->{'new_password'} ne $p->{'new_password2'};
2964 return { 'error' => 'Enter new password' }
2965 unless length($p->{'new_password'});
2967 #my $search = { 'custnum' => $custnum };
2968 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2969 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2970 my $search = " AND custnum = $1";
2971 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2973 my $svc_acct = qsearchs( {
2974 'table' => 'svc_acct',
2975 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2976 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2977 'LEFT JOIN cust_main USING ( custnum ) ',
2978 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2979 'extra_sql' => $search, #important
2981 or return { 'error' => "Service not found" };
2985 my $conf = new FS::Conf;
2987 return { 'error' => 'Incorrect current password.' }
2988 if ( exists($p->{'old_password'})
2989 || $conf->exists('selfservice-password_change_oldpass')
2991 && ! $svc_acct->check_password($p->{'old_password'});
2993 $error = 'Password too short.'
2994 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2995 $error = 'Password too long.'
2996 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2998 $svc_acct->set_password($p->{'new_password'});
2999 $error ||= $svc_acct->replace();
3001 #regular pw change in self-service should change contact pw too, otherwise its
3002 #way too confusing. hell its confusing they're separate at all, but alas.
3003 #need to support the "ISP provides email that's used as a contact email" case
3005 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3006 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3007 custnum => $custnum,
3008 selfservice_access => 'Y',
3012 #svc_acct was successful but this one returns an error? "shouldn't happen"
3013 $error ||= $contact->change_password($p->{'new_password'});
3016 my($label, $value) = $svc_acct->cust_svc->label;
3018 return { 'error' => $error,
3028 my $info = skin_info($p);
3030 my $conf = new FS::Conf;
3031 my $verification = $conf->config('selfservice-password_reset_verification')
3032 or return { %$info, 'error' => 'Password resets disabled' };
3037 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3039 $contact = FS::contact->by_selfservice_email($p->{'email'});
3042 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3043 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3046 #also look for an svc_acct, otherwise it would be super confusing
3048 my($username, $domain) = split('@', $p->{'email'});
3049 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3050 if ( $svc_domain ) {
3051 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3052 'domsvc' => $svc_domain->svcnum }
3055 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3056 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3058 #precaution: don't change svc_acct password not part of the same
3059 # customer as contact
3060 $svc_acct = '' if ! $cust_pkg
3061 || $cust_pkg->custnum != $cust_main->custnum;
3066 return { %$info, 'error' => 'Email address not found' }
3067 unless $contact || $svc_acct;
3069 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3071 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3072 or return { %$info, 'error' => 'Account not found' };
3074 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3075 'domsvc' => $svc_domain->svcnum }
3077 or return { %$info, 'error' => 'Account not found' };
3079 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3080 or return { %$info, 'error' => 'Account not found' };
3082 $cust_main = $cust_pkg->cust_main;
3086 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3087 if ! $cust_main && $verification ne 'email';
3090 'email' => sub { 1; },
3092 my( $p, $cust_main ) = @_;
3093 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3094 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3097 my( $p, $cust_main ) = @_;
3098 my $cust_pay = qsearchs({
3099 'table' => 'cust_pay',
3100 'hashref' => { 'custnum' => $cust_main->custnum },
3101 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3105 $p->{'amount'} == $cust_pay->paid;
3108 my( $p, $cust_main ) = @_;
3109 $p->{'zip'} eq $cust_main->zip
3110 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3114 foreach my $verify ( split(',', $verification) ) {
3116 &{ $verify{$verify} }( $p, $cust_main )
3117 or return { %$info, 'error' => 'Account not found' };
3121 #okay, we're verified
3125 my $error = $contact->send_reset_email(
3126 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3130 return { %$info, 'error' => $error }; #????
3133 } elsif ( $svc_acct ) {
3135 #create a unique session
3137 my $reset_session = {
3138 'svcnum' => $svc_acct->svcnum,
3139 'agentnum' => $svc_acct->cust_main->agentnum,
3142 my $timeout = '1 hour'; #?
3144 my $reset_session_id;
3146 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3147 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3150 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3154 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3155 $cust_main->agentnum);
3156 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3157 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3159 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3160 my $error = $msg_template->send( 'cust_main' => $cust_main,
3161 'object' => $svc_acct,
3162 'substitutions' => {
3163 'session_id' => $reset_session_id,
3167 return { %$info, 'error' => $error }; #????
3172 return { %$info, 'error' => '' };
3175 sub check_reset_passwd {
3178 my $conf = new FS::Conf;
3179 my $verification = $conf->config('selfservice-password_reset_verification')
3180 or return { 'error' => 'Password resets disabled' };
3182 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3183 or return { 'error' => "Can't resume session" }; #better error message
3185 if ( $reset_session->{'svcnum'} ) {
3187 my $svcnum = $reset_session->{'svcnum'};
3189 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3190 or return { 'error' => "Service not found" };
3192 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3193 my $info = skin_info($p);
3197 'session_id' => $p->{'session_id'},
3198 'username' => $svc_acct->username,
3201 } elsif ( $reset_session->{'contactnum'} ) {
3203 my $contactnum = $reset_session->{'contactnum'};
3205 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3206 or return { 'error' => "Contact not found" };
3208 my @contact_email = $contact->contact_email;
3209 return { 'error' => 'No contact email' } unless @contact_email;
3211 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3212 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3213 if scalar(@cust_contact) == 1;
3214 my $info = skin_info($p);
3218 'session_id' => $p->{'session_id'},
3219 'email' => $contact_email[0]->email, #the first?
3224 return { 'error' => 'No svcnum or contactnum in session' }; #??
3230 sub process_reset_passwd {
3233 my $conf = new FS::Conf;
3234 my $verification = $conf->config('selfservice-password_reset_verification')
3235 or return { 'error' => 'Password resets disabled' };
3237 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3238 or return { 'error' => "Can't resume session" }; #better error message
3243 if ( $reset_session->{'svcnum'} ) {
3245 my $svcnum = $reset_session->{'svcnum'};
3247 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3248 or return { 'error' => "Service not found" };
3250 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3251 $info ||= skin_info($p);
3256 if ( $reset_session->{'contactnum'} ) {
3258 my $contactnum = $reset_session->{'contactnum'};
3260 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3261 or return { 'error' => "Contact not found" };
3263 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3264 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3265 if scalar(@cust_contact) == 1;
3266 $info ||= skin_info($p);
3270 return { %$info, 'error' => "New passwords don't match." }
3271 if $p->{'new_password'} ne $p->{'new_password2'};
3273 return { %$info, 'error' => 'Enter new password' }
3274 unless length($p->{'new_password'});
3278 $svc_acct->set_password($p->{'new_password'});
3279 my $error = $svc_acct->replace();
3281 return { %$info, 'error' => $error } if $error;
3283 #my($label, $value) = $svc_acct->cust_svc->label;
3284 #return { 'error' => $error,
3285 # #'label' => $label,
3286 # #'value' => $value,
3293 my $error = $contact->change_password($p->{'new_password'});
3295 return { %$info, 'error' => $error }; # if $error;
3299 #password changed ,so remove session, don't want it reused
3300 _cache->remove($p->{'session_id'});
3302 return { %$info, 'error' => '' };
3308 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3309 return { 'error' => $session } if $context eq 'error';
3312 if ( $session->{'pkgnum'} ) {
3314 #tickets for specific service with pkg-balances on
3315 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3316 'pkgnum' => $session->{'pkgnum'} })
3317 or return { 'error' => 'unknown package' };
3318 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3319 push @tickets, $cust_svc->tickets( $p->{status} );
3324 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3325 or return { 'error' => "unknown custnum $custnum" };
3327 @tickets = $cust_main->tickets( $p->{status} );
3330 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3331 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3332 my $conf = new FS::Conf;
3333 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3337 ($a->{'_selfservice_priority'} eq '') <=>
3338 ($b->{'_selfservice_priority'} eq '')
3341 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3347 +{ tickets => \@tickets };
3354 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3355 return { 'error' => $session } if $context eq 'error';
3357 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3358 FS::TicketSystem->init();
3360 my $conf = new FS::Conf;
3361 my $queue = $p->{'queue'}
3362 || $conf->config('ticket_system-selfservice_queueid')
3363 || $conf->config('ticket_system-default_queueid');
3365 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3366 my $err_or_ticket = FS::TicketSystem->create_ticket(
3367 '', #create RT session based on FS CurrentUser (fs_selfservice)
3369 'custnum' => $custnum,
3370 'svcnum' => $session->{'svcnum'},
3371 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3374 if ( ref($err_or_ticket) ) {
3375 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3377 return { 'error' => '',
3378 'ticket_id' => $err_or_ticket->id,
3381 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3383 return { 'error' => $err_or_ticket };
3391 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3392 return { 'error' => $session } if $context eq 'error';
3394 return { error => 'requested format not implemented' }
3395 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3397 my $conf = new FS::Conf;
3398 my $age_threshold = 0;
3399 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3400 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3402 my $search = { 'custnum' => $custnum };
3403 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3404 my $cust_main = qsearchs('cust_main', $search )
3405 or return { 'error' => "unknown custnum $custnum" };
3407 # does it make more sense to just run one sql query for this instead of all the
3408 # insanity below? would increase performance greately for large data sets?
3410 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3411 my @part_svc = $cust_pkg->part_svc;
3412 foreach my $part_svc ( @part_svc ) {
3413 if($part_svc->svcdb eq 'svc_phone'){
3414 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3415 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3416 push @svc_phone, $cust_pkg_svc->svc_x
3417 if $cust_pkg_svc->date_inserted >= $age_threshold;
3425 my($xls_r,$xls_c) = (0,0);
3428 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3429 if($p->{'format'} eq 'csv') {
3430 $csv = new Text::CSV_XS { 'always_quote' => 1,
3433 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3434 $content .= $csv->string;
3436 elsif($p->{'format'} eq 'xls') {
3437 my $XLS1 = new IO::Scalar \$content;
3438 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3439 or return { 'error' => "Error opening .xls file: $!" };
3440 $xls = $xls_workbook->add_worksheet('DIDs');
3441 foreach ( @fields ) {
3442 $xls->write(0,$xls_c++,$_);
3447 foreach my $svc_phone ( @svc_phone ) {
3448 my @cols = map { $svc_phone->$_ } @fields;
3449 if($p->{'format'} eq 'csv') {
3450 return { 'error' => 'Unable to create CSV' }
3451 unless $csv->combine(@cols);
3452 $content .= $csv->string;
3454 elsif($p->{'format'} eq 'xls') {
3457 $xls->write($xls_r,$xls_c++,$_);
3463 $xls_workbook->close() if $p->{'format'} eq 'xls';
3465 { content => $content, format => $p->{'format'}, };
3470 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3471 return { 'error' => $session } if $context eq 'error';
3473 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3474 # FS::TicketSystem->init();
3475 # return { 'error' => 'get_ticket configuration error' }
3476 # if $FS::TicketSystem::system ne 'RT_Internal';
3478 # check existence and ownership as part of this
3479 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3480 my $rt_session = FS::TicketSystem->session('');
3481 my $Ticket = FS::TicketSystem->get_ticket_object(
3483 ticket_id => $p->{'ticket_id'},
3486 return { 'error' => 'ticket not found' } if !$Ticket;
3488 if ( length( $p->{'subject'} || '' ) ) {
3490 if ( $p->{'subject'} ne $Ticket->Subject ) {
3491 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3492 return { 'error' => "unable to set subject: $msg" } if !$val;
3496 if(length($p->{'reply'})) {
3497 my @err_or_res = FS::TicketSystem->correspond_ticket(
3499 'ticket_id' => $p->{'ticket_id'},
3500 'content' => $p->{'reply'},
3503 return { 'error' => 'unable to reply to ticket' }
3504 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3507 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3508 my $err_or_ticket = FS::TicketSystem->get_ticket(
3510 'ticket_id' => $p->{'ticket_id'},
3513 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3514 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3516 return { 'error' => $err_or_ticket };
3519 my @custs = @{$err_or_ticket->{'custs'}};
3520 my @txns = @{$err_or_ticket->{'txns'}};
3523 # superseded by check in get_ticket_object
3524 #return { 'error' => 'invalid ticket requested' }
3525 #unless grep($_ eq $custnum, @custs);
3527 foreach my $txn ( @txns ) {
3528 push @filtered_txns, $txn
3529 if ($txn->{'type'} eq 'EmailRecord'
3530 || $txn->{'type'} eq 'Correspond'
3531 || $txn->{'type'} eq 'Create');
3534 warn "$me get_ticket: successful: \n"
3536 return { 'error' => '',
3537 'transactions' => \@filtered_txns,
3538 'ticket_fields' => $err_or_ticket->{'fields'},
3539 'ticket_id' => $p->{'ticket_id'},
3543 sub adjust_ticket_priority {
3545 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3546 return { 'error' => $session } if $context eq 'error';
3548 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3549 # FS::TicketSystem->init;
3550 my $ss_priority = FS::TicketSystem->selfservice_priority;
3552 return { 'error' => 'adjust_ticket_priority configuration error' }
3553 if $FS::TicketSystem::system ne 'RT_Internal'
3556 my $values = $p->{'values'}; #hashref, id => priority value
3559 foreach my $id (keys %$values) {
3560 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3561 my $Ticket = FS::TicketSystem->get_ticket_object('',
3563 'custnum' => $custnum,
3566 $ticket_error{$id} = 'ticket not found';
3570 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3571 # We're not going to implement it for RT_External.
3572 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3573 my $new_value = $values->{$id};
3574 next if $old_value eq $new_value;
3576 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3578 # AddCustomFieldValue works fine (replacing any existing value) if it's
3579 # a single-valued custom field, which it should be. If it's not, you're
3580 # doing something wrong.
3582 if ( length($new_value) ) {
3583 ($val, $msg) = $Ticket->AddCustomFieldValue(
3584 Field => $ss_priority,
3585 Value => $new_value,
3589 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3590 Field => $ss_priority,
3591 Value => $old_value,
3595 $ticket_error{$id} = $msg if !$val;
3596 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3598 return { 'error' => '',
3599 'ticket_error' => \%ticket_error,
3600 %{ customer_info($p) } # send updated customer info back
3606 sub _custoragent_session_custnum {
3609 my($context, $session, $custnum);
3610 if ( $p->{'session_id'} ) {
3612 $context = 'customer';
3613 $session = _cache->get($p->{'session_id'})
3614 or return ( 'error' => "Can't resume session" ); #better error message
3615 $custnum = $session->{'custnum'};
3617 } elsif ( $p->{'agent_session_id'} ) {
3620 my $agent_cache = new FS::ClientAPI_SessionCache( {
3621 'namespace' => 'FS::ClientAPI::Agent',
3623 $session = $agent_cache->get($p->{'agent_session_id'})
3624 or return ( 'error' => "Can't resume session" ); #better error message
3625 $custnum = $p->{'custnum'};
3629 return ( 'error' => "Can't resume session" ); #better error message
3632 ($context, $session, $custnum);