1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
58 $me = '[FS::ClientAPI::MyAccount]';
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62 first last company daytime night fax mobile
64 ss stateid stateid_state
66 @location_editable_fields = qw(
67 address1 address2 city county state zip country
71 BEGIN { #preload to reduce time customer_info takes
72 if ( $FS::TicketSystem::system ) {
73 warn "$me: initializing ticket system\n" if $DEBUG;
74 FS::TicketSystem->init();
79 $cache ||= new FS::ClientAPI_SessionCache( {
80 'namespace' => 'FS::ClientAPI::MyAccount',
87 my($context, $session, $custnum) = _custoragent_session_custnum($p);
88 #return { 'error' => $session } if $context eq 'error';
91 if ( $context eq 'customer' && $custnum ) {
93 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
96 $sth->execute($custnum) or die $sth->errstr;
98 $agentnum = $sth->fetchrow_arrayref->[0]
99 or die "no agentnum for custnum $custnum";
101 #} elsif ( $context eq 'agent' ) {
102 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
105 $p->{'agentnum'} = $agentnum;
107 my $conf = new FS::Conf;
109 #false laziness w/Signup.pm
111 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
113 if ( $skin_info_cache_agent ) {
115 warn "$me loading cached skin info for agentnum $agentnum\n"
120 warn "$me populating skin info cache for agentnum $agentnum\n"
123 $skin_info_cache_agent = {
124 'agentnum' => $agentnum,
125 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
126 qw( company_name date_format ) ),
127 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
128 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
129 text_color link_color vlink_color hlink_color alink_color
130 font title_color title_align title_size menu_bgcolor menu_fontsize
133 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
134 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
135 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
137 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
138 qw( title_left_image title_right_image
139 menu_top_image menu_body_image menu_bottom_image
142 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
143 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
144 qw( head body_header body_footer company_address ) ),
145 'money_char' => $conf->config("money_char") || '$',
146 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
149 services.php Services
150 services.php My Services
151 services_new.php Order a new service
154 personal.php Personal Information
155 password.php Change Password
158 payment_cc.php Credit Card Payment
159 payment_ach.php Electronic Check Payment
160 payment_paypal.php PayPal Payment
161 payment_webpay.php Webpay Payments
164 usage_data.php Data usage
165 usage_cdr.php Call usage
167 tickets.php Help Desk
168 tickets.php Open Tickets
169 tickets_resolved.php Resolved Tickets
170 ticket_create.php Create a new ticket
178 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
182 #{ %$skin_info_cache_agent };
183 $skin_info_cache_agent;
190 my $conf = new FS::Conf;
194 'phone_login' => $conf->exists('selfservice_server-phone_login'),
195 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
196 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
197 'banner_image_md5' =>
198 md5_hex($conf->config_binary('selfservice-login_banner_image')),
205 sub login_banner_image {
207 my $conf = new FS::Conf;
208 my $image = $conf->config_binary('selfservice-login_banner_image');
210 'md5' => md5_hex($image),
215 #false laziness w/FS::ClientAPI::passwd::passwd
219 my $conf = new FS::Conf;
223 if ( $p->{'domain'} eq 'svc_phone'
224 && $conf->exists('selfservice_server-phone_login') ) {
226 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
227 return { error => 'Number not found.' } unless $svc_phone;
230 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
231 #return { error => 'Only primary user may log in.' }
232 # if $conf->exists('selfservice_server-primary_only')
233 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
235 return { error => 'Incorrect PIN.' }
236 unless $svc_phone->check_pin($p->{'password'});
240 } elsif ( $p->{email}
241 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
244 return { error => 'Incorrect contact password.' }
245 unless $contact->authenticate_password($p->{'password'});
247 $session->{'contactnum'} = $contact->contactnum;
249 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
250 if ( scalar(@cust_contact) == 1 ) {
251 $session->{'custnum'} = $cust_contact[0]->custnum;
252 } elsif ( scalar(@cust_contact) ) {
253 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
257 return { error => 'No customer self-service access for contact' }; #??
262 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
264 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
265 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
267 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
268 'domsvc' => $svc_domain->svcnum, }
271 if ( $conf->exists('selfservice_server-login_svcpart') ) {
272 my @svcpart = $conf->config('selfservice_server-login_svcpart');
273 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
274 scalar( grep( $_ eq $svcpart, @svcpart ) );
279 if ( $conf->exists('selfservice_server-primary_only') ) {
282 my $cust_svc = $_->cust_svc;
283 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
284 == $cust_svc->svcpart
289 return { error => 'User not found.' } unless @svc_acct;
291 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
293 my $svc_acct = $svc_acct[0];
295 if ( $conf->exists('selfservice_server-login_svcpart') ) {
296 my @svcpart = $conf->config('selfservice_server-login_svcpart');
297 my $svcpart = $svc_acct->cust_svc->svcpart;
298 return { error => 'Invalid user.' }
299 unless grep($_ eq $svcpart, @svcpart);
302 return { error => 'Incorrect password.' }
303 unless $svc_acct->check_password($p->{'password'});
311 $session->{'svcnum'} = $svc_x->svcnum;
313 my $cust_svc = $svc_x->cust_svc;
314 my $cust_pkg = $cust_svc->cust_pkg;
316 my $cust_main = $cust_pkg->cust_main;
317 $session->{'custnum'} = $cust_main->custnum;
318 if ( $conf->exists('pkg-balances') ) {
319 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
320 $cust_main->ncancelled_pkgs;
321 $session->{'pkgnum'} = $cust_pkg->pkgnum
322 if scalar(@cust_pkg) > 1;
326 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
327 #return { error => 'Only primary user may log in.' }
328 # if $conf->exists('selfservice_server-primary_only')
329 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
330 my $part_pkg = $cust_pkg->part_pkg;
331 return { error => 'Only primary user may log in.' }
332 if $conf->exists('selfservice_server-primary_only')
333 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
339 $session_id = sha512_hex(time(). {}. rand(). $$)
340 } until ( ! defined _cache->get($session_id) ); #just in case
342 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
343 _cache->set( $session_id, $session, $timeout );
345 return { 'error' => '',
346 'session_id' => $session_id,
353 my $skin_info = skin_info($p);
354 if ( $p->{'session_id'} ) {
355 _cache->remove($p->{'session_id'});
356 return { %$skin_info, 'error' => '' };
358 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
365 my($context, $session, $custnum) = _custoragent_session_custnum($p);
366 return { 'error' => $session } if $context eq 'error';
368 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
369 or return { 'error' => "Service not found" };
371 $session->{'svcnum'} = $svc_acct->svcnum;
373 my $conf = new FS::Conf;
374 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
375 _cache->set( $p->{'session_id'}, $session, $timeout );
377 return { 'error' => '' };
383 my($context, $session, $custnum) = _custoragent_session_custnum($p);
384 return { 'error' => $session } if $context eq 'error';
386 $session->{'custnum'} = $p->{'custnum'}
387 if exists $session->{'customers'}{ $p->{'custnum'} };
389 my $conf = new FS::Conf;
390 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
391 _cache->set( $p->{'session_id'}, $session, $timeout );
393 return { 'error' => '',
394 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
398 sub payment_gateway {
400 # takes a cust_main and a cust_payby entry, returns the payment_gateway
401 my $conf = new FS::Conf;
402 my $cust_main = shift;
403 my $cust_payby = shift;
404 my $gatewaynum = $conf->config('selfservice-payment_gateway');
406 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
407 die "configured gatewaynum $gatewaynum not found!" if !$pg;
411 return '' if ! FS::payby->realtime($cust_payby);
412 my $pg = $cust_main->agent->payment_gateway(
413 'method' => FS::payby->payby2bop($cust_payby),
423 my $conf = new FS::Conf;
425 my $info = skin_info($p);
427 use vars qw( $cust_paybys ); #cache for performance
428 unless ( $cust_paybys ) {
430 my %cust_paybys = map { $_ => 1 }
431 map { FS::payby->payby2payment($_) }
432 $conf->config('signup_server-payby');
434 $cust_paybys = [ keys %cust_paybys ];
437 $info->{'cust_paybys'} = $cust_paybys;
439 my($context, $session, $custnum) = _custoragent_session_custnum($p);
440 return { 'error' => $session } if $context eq 'error';
442 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
444 $info->{'hide_payment_fields'} = [
446 my $pg = $cust_main && payment_gateway($cust_main, $_);
447 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
448 } @{ $info->{cust_paybys} }
451 $info->{'self_suspend_reason'} =
452 $conf->config('selfservice-self_suspend_reason',
453 $cust_main ? $cust_main->agentnum : ''
456 $info->{'edit_ticket_subject'} =
457 $conf->exists('ticket_system-selfservice_edit_subject') &&
458 $cust_main && $cust_main->edit_subject;
460 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
462 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
465 'custnum' => $custnum,
466 'access_pkgnum' => $session->{'pkgnum'},
467 'access_svcnum' => $session->{'svcnum'},
474 my($context, $session, $custnum) = _custoragent_session_custnum($p);
475 return { 'error' => $session } if $context eq 'error';
479 my $conf = new FS::Conf;
480 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
482 # if ( $FS::TicketSystem::system ) {
483 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
484 # FS::TicketSystem->init();
487 if ( $custnum ) { #customer record
489 %return = ( %return, %{ customer_info_short($p) } );
491 #redundant with customer_info_short, but we need it for several things below
492 my $search = { 'custnum' => $custnum };
493 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
494 my $cust_main = qsearchs('cust_main', $search )
495 or return { 'error' => "customer_info: unknown custnum $custnum" };
497 my $list_tickets = list_tickets($p);
498 $return{'tickets'} = $list_tickets->{'tickets'};
500 if ( $session->{'pkgnum'} ) {
501 #XXX open invoices in the pkg-balances case
503 $return{'money_char'} = $conf->config("money_char") || '$';
506 invnum => $_->invnum,
507 date => time2str("%b %o, %Y", $_->_date),
509 charged => $_->charged,
511 } $cust_main->open_cust_bill;
512 $return{open_invoices} = \@open;
514 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
515 my $sth = dbh->prepare($sql) or die dbh->errstr;
516 $sth->execute($custnum) or die $sth->errstr;
517 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
518 $return{'last_invoice_date_pretty'} =
519 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
522 #customer_info_short always has nobalance on..
523 $return{small_custview} =
524 small_custview( $cust_main,
525 $return{countrydefault},
526 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
529 $return{has_ship_address} = $cust_main->has_ship_address;
530 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
531 $return{statuscolor} = $cust_main->statuscolor;
532 $return{status_label} = $cust_main->status_label;
534 # compatibility: some places in selfservice use this to determine
535 # if there's a ship address
536 if ( $return{has_ship_address} ) {
537 $return{ship_last} = $cust_main->last;
538 $return{ship_first} = $cust_main->first;
541 if (scalar($conf->config('support_packages'))) {
542 my @support_services = ();
543 foreach ($cust_main->support_services) {
544 my $seconds = $_->svc_x->seconds || 0;
545 my $time_remaining = (($seconds < 0) ? '-' : '' ).
546 int(abs($seconds)/3600)."h".
547 sprintf("%02d",(abs($seconds)%3600)/60)."m";
548 my $cust_pkg = $_->cust_pkg;
551 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
552 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
553 push @support_services, { svcnum => $_->svcnum,
554 time => $time_remaining,
559 $return{support_services} = \@support_services;
562 if ( $conf->config('prepayment_discounts-credit_type') ) {
564 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
567 } elsif ( $session->{'svcnum'} ) { #no customer record
569 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
570 or die "unknown svcnum";
571 $return{name} = $svc_acct->email;
575 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
579 return { 'error' => '',
580 'custnum' => $custnum,
586 sub customer_info_short {
589 my($context, $session, $custnum) = _custoragent_session_custnum($p);
590 return { 'error' => $session } if $context eq 'error';
594 my $conf = new FS::Conf;
596 if ( $custnum ) { #customer record
598 my $search = { 'custnum' => $custnum };
599 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
600 my $cust_main = qsearchs('cust_main', $search )
601 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
603 $return{display_custnum} = $cust_main->display_custnum;
605 if ( $session->{'pkgnum'} ) {
606 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
607 #next_bill_date from cust_pkg?
609 $return{balance} = $cust_main->balance;
610 $return{next_bill_date} = $cust_main->next_bill_date;
611 $return{next_bill_date_pretty} =
612 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
615 $return{balance_pretty} = money_pretty($return{balance});
617 $return{countrydefault} = scalar($conf->config('countrydefault'));
619 $return{small_custview} =
620 small_custview( $cust_main,
621 $return{countrydefault},
625 $return{first} = $cust_main->first;
626 $return{'last'} = $cust_main->get('last');
627 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
629 #none of these are terribly expensive if we want 'em...
630 for (@cust_main_editable_fields) {
631 $return{$_} = $cust_main->get($_);
633 #maybe a little more expensive, but it should be cached by now
634 for (@location_editable_fields) {
635 $return{$_} = $cust_main->bill_location->get($_)
636 if $cust_main->bill_locationnum;
637 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
638 if $cust_main->ship_locationnum;
641 my @invoicing_list = $cust_main->invoicing_list;
642 $return{'invoicing_list'} =
643 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
644 $return{'postal_invoicing'} =
645 0 < ( grep { $_ eq 'POST' } @invoicing_list );
647 if ( $session->{'svcnum'} ) {
648 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
649 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
650 $return{'svcnum'} = $session->{'svcnum'};
653 } elsif ( $session->{'svcnum'} ) { #no customer record
655 #uuh, not supproted yet... die?
656 return { 'error' => 'customer_info_short not yet supported as agent' };
660 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
664 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
665 # it is not customer-specific, though it is only shown to authenticated customers
666 # it is not currently agent-specific, though at some point it might be
667 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
669 return { 'error' => '',
670 'custnum' => $custnum,
675 sub billing_history {
678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
679 return { 'error' => $session } if $context eq 'error';
681 return { 'error' => 'No customer' } unless $custnum;
683 my $search = { 'custnum' => $custnum };
684 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
685 my $cust_main = qsearchs('cust_main', $search )
686 or return { 'error' => "unknown custnum $custnum" };
690 if ( $session->{'pkgnum'} ) {
691 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
692 #next_bill_date from cust_pkg?
693 return { 'error' => 'No history for package' };
696 $return{balance} = $cust_main->balance;
697 $return{balance_pretty} = money_pretty($return{balance});
698 $return{next_bill_date} = $cust_main->next_bill_date;
699 $return{next_bill_date_pretty} =
700 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
703 my $conf = new FS::Conf;
705 $return{'history'} = [
706 $cust_main->payment_history(
707 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
712 $return{'money_char'} = $conf->config("money_char") || '$',
720 my $session = _cache->get($p->{'session_id'})
721 or return { 'error' => "Can't resume session" }; #better error message
723 my $custnum = $session->{'custnum'}
724 or return { 'error' => "no customer record" };
726 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
727 or return { 'error' => "unknown custnum $custnum" };
729 my $new = new FS::cust_main { $cust_main->hash };
731 $new->set( $_ => $p->{$_} )
732 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
734 if ( exists($p->{address1}) ) {
735 my $bill_location = FS::cust_location->new({
736 map { $_ => $p->{$_} } @location_editable_fields
738 # if this is unchanged from before, cust_main::replace will ignore it
739 $new->set('bill_location' => $bill_location);
742 if ( exists($p->{ship_address1}) ) {
743 my $ship_location = FS::cust_location->new({
744 map { $_ => $p->{"ship_$_"} } @location_editable_fields
746 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
747 # Selfservice unfortunately tries to indicate "same as billing
748 # address" by sending all fields empty. Did this ever work?
749 $ship_location = $cust_main->bill_location;
751 $new->set('ship_location' => $ship_location);
753 # but if it hasn't been passed in at all, leave ship_location alone--
754 # DON'T change it to match bill_location.
756 my $conf = new FS::Conf;
759 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
760 #false laziness with httemplate/edit/process/cust_main.cgi
761 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
762 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
764 @invoicing_list = $cust_main->invoicing_list;
767 my $error = $new->replace($cust_main, \@invoicing_list);
768 return { 'error' => $error } if $error;
771 return { 'error' => '' };
776 my $session = _cache->get($p->{'session_id'})
777 or return { 'error' => "Can't resume session" }; #better error message
783 my $conf = new FS::Conf;
784 use vars qw($payment_info); #cache for performance
785 unless ( $payment_info ) {
787 my %states = map { $_->state => 1 }
788 qsearch('cust_main_county', {
789 'country' => $conf->config('countrydefault') || 'US'
792 my %cust_paybys = map { $_ => 1 }
793 map { FS::payby->payby2payment($_) }
794 $conf->config('signup_server-payby');
796 my @cust_paybys = keys %cust_paybys;
800 #list all counties/states/countries
801 'cust_main_county' =>
802 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
804 #shortcut for one-country folks
806 [ sort { $a cmp $b } keys %states ],
808 'card_types' => card_types(),
810 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
811 'require_cvv' => $conf->exists('selfservice-require_cvv'),
812 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
814 'paytypes' => [ FS::cust_payby::paytypes ],
816 'paybys' => [ $conf->config('signup_server-payby') ],
817 'cust_paybys' => \@cust_paybys,
819 'stateid_label' => FS::Msgcat::_gettext('stateid'),
820 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
822 'show_ss' => $conf->exists('show_ss'),
823 'show_stateid' => $conf->exists('show_stateid'),
824 'show_paystate' => $conf->exists('show_bankstate'),
826 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
828 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
837 my %return = %$payment_info;
839 my $custnum = $session->{'custnum'};
841 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
842 or return { 'error' => "unknown custnum $custnum" };
844 $return{'hide_payment_fields'} = [
846 my $pg = payment_gateway($cust_main, $_);
847 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
848 } @{ $return{cust_paybys} }
851 $return{balance} = $cust_main->balance; #XXX pkg-balances?
853 $return{$_} = $cust_main->bill_location->get($_)
854 for qw(address1 address2 city state zip);
856 # look for stored cust_payby info
857 # only if we've been given a clear payment_payby (to avoid payname conflicts)
858 if ($p->{'payment_payby'} =~ /^(CARD|CHEK)$/) {
859 my @search_payby = ($p->{'payment_payby'} eq 'CARD') ? ('CARD','DCRD') : ('CHEK','DCHK');
860 my ($cust_payby) = $cust_main->cust_payby(@search_payby);
862 $return{payname} = $cust_payby->payname
863 || ( $cust_main->first. ' '. $cust_main->get('last') );
865 if ( $cust_payby->payby =~ /^(CARD|DCRD)$/ ) {
866 $return{card_type} = cardtype($cust_payby->payinfo);
867 $return{payinfo} = $cust_payby->paymask;
869 @return{'month', 'year'} = $cust_payby->paydate_monthyear;
873 if ( $cust_payby->payby =~ /^(CHEK|DCHK)$/ ) {
874 my ($payinfo1, $payinfo2) = split '@', $cust_payby->paymask;
875 $return{payinfo1} = $payinfo1;
876 $return{payinfo2} = $payinfo2;
877 $return{paytype} = $cust_payby->paytype;
878 $return{paystate} = $cust_payby->paystate;
879 $return{payname} = $cust_payby->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
884 if ( $conf->config('prepayment_discounts-credit_type') ) {
886 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
889 #doubleclick protection
891 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
892 $return{paybatch} = $return{payunique}; #back compat
894 return { 'error' => '',
900 #some false laziness with httemplate/process/payment.cgi - look there for
901 #ACH and CVV support stuff
903 sub validate_payment {
906 my $session = _cache->get($p->{'session_id'})
907 or return { 'error' => "Can't resume session" }; #better error message
909 my $custnum = $session->{'custnum'};
911 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
912 or return { 'error' => "unknown custnum $custnum" };
914 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
915 or return { 'error' => gettext('illegal_amount') };
917 return { error => 'Amount must be greater than 0' } unless $amount > 0;
919 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
920 #changing the hidden form values
921 my $conf = new FS::Conf;
922 my $fee_display = $conf->config('selfservice_process-display') || 'add';
923 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
924 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
925 if ( $fee_display eq 'add'
927 and ! $fee_skip_first || scalar($cust_main->cust_pay)
930 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
931 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
934 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
935 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
936 my $discount_term = $1;
938 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
939 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
942 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
943 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
946 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
947 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
950 $payunique = $paybatch if ! length($payunique) && length($paybatch);
952 $p->{'payby'} ||= 'CARD';
953 $p->{'payby'} =~ /^([A-Z]{4})$/
954 or return { 'error' => "illegal_payby " . $p->{'payby'} };
957 #false laziness w/process/payment.cgi
960 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
962 $p->{'payinfo1'} =~ /^([\dx]+)$/
963 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
965 $p->{'payinfo2'} =~ /^([\dx]+)$/
966 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
968 $payinfo = $payinfo1. '@'. $payinfo2;
970 foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
971 if ( $cust_payby->paymask eq $payinfo ) {
972 $payinfo = $cust_payby->payinfo;
977 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
979 $payinfo = $p->{'payinfo'};
983 #more intelligent matching will be needed here if you change
984 #card_masking_method and don't remove existing paymasks
985 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
986 if ( $cust_payby->paymask eq $payinfo ) {
987 $payinfo = $cust_payby->payinfo;
994 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
995 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
999 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1000 return { 'error' => gettext('unknown_card_type') }
1001 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1003 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1004 if ( cardtype($payinfo) eq 'American Express card' ) {
1005 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1006 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1009 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1010 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1013 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1014 return { 'error' => 'CVV2 is required' };
1015 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1016 return { 'error' => 'CVV2 is required' };
1020 die "unknown payby $payby";
1023 my %payby2fields = (
1024 'CARD' => [ qw( paystart_month paystart_year payissue payip
1025 address1 address2 city state zip country ) ],
1026 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1030 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1033 'cust_main' => $cust_main, #XXX or just custnum??
1034 'amount' => sprintf('%.2f', $amount),
1036 'payinfo' => $payinfo,
1037 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1038 'card_type' => $card_type,
1039 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1040 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1041 'month' => $p->{'month'},
1042 'year' => $p->{'year'},
1043 'payname' => $payname,
1044 'payunique' => $payunique,
1045 'paybatch' => $paybatch,
1046 'paycvv' => $paycvv,
1047 'payname' => $payname,
1048 'discount_term' => $discount_term,
1049 'pkgnum' => $session->{'pkgnum'},
1050 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1060 my $validate = validate_payment($p);
1061 return $validate if $validate->{'error'};
1063 my $conf = new FS::Conf;
1064 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1065 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1067 +{ map { $_=>$validate->{$_} }
1068 qw( card_type paymask payname paydate_pretty month year amount
1069 address1 address2 city state zip country
1075 sub process_stored_payment {
1078 my $session_id = $p->{'session_id'};
1080 my $payment_info = _cache->get( "payment_$session_id" )
1081 or return { 'error' => "Can't resume session" }; #better error message
1083 do_process_payment($payment_info);
1087 sub process_payment {
1090 my $payment_info = validate_payment($p);
1091 return $payment_info if $payment_info->{'error'};
1093 do_process_payment($payment_info);
1097 sub do_process_payment {
1098 my $validate = shift;
1100 my $cust_main = $validate->{'cust_main'};
1102 my $amount = delete $validate->{'amount'};
1105 my $payby = delete $validate->{'payby'};
1107 if ( $validate->{'save'} ) {
1110 foreach my $field ( qw( auto payinfo paymask payname payip ) ) {
1111 $saveopt{$field} = $validate->{$field};
1114 if ( $payby eq 'CARD' ) {
1115 my $bill_location = FS::cust_location->new({
1116 map { $_ => $validate->{$_} }
1117 qw(address1 address2 city state country zip)
1119 $saveopt{'bill_location'} = $bill_location;
1120 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
1121 $saveopt{$field} = $validate->{$field};
1124 # stateid/stateid_state won't be saved, might be broken as of 4.x
1125 foreach my $field ( qw( paytype paystate ) ) {
1126 $saveopt{$field} = $validate->{$field};
1130 my $error = $cust_main->save_cust_payby(
1131 'payment_payby' => $payby,
1136 #no, this causes customers to process their payments again
1137 #return { 'error' => $error };
1138 #XXX just warn verosely for now so i can figure out how these happen in
1139 # the first place, eventually should redirect them to the "change
1140 #address" page but indicate if the payment processed?
1141 delete($validate->{'payinfo'}); #don't want to log this!
1142 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1144 "SAVEOPT: ".Dumper(\%saveopt)."\n".
1145 "CUST_MAIN: ". Dumper($cust_main)."\n".
1146 "PACKET: ". Dumper($validate)."\n";
1150 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1154 'paynum_ref' => \$paynum,
1157 return { 'error' => $error } if $error;
1159 #no error, so order the fee package if applicable...
1160 my $conf = new FS::Conf;
1161 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1162 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1164 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1166 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1168 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1169 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1172 #and generate an invoice for it now too
1173 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1174 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1179 $cust_main->apply_payments;
1182 my $receipt_html = '';
1184 # currently supported for realtime CC only; send receipt data to SS
1185 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1188 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1191 <TD ALIGN="right">Payment#</TD>
1192 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1196 <TD ALIGN="right">Date</TD>
1198 <TD BGCOLOR="#FFFFFF"><B>! .
1199 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1205 <TD ALIGN="right">Amount</TD>
1206 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1211 <TD ALIGN="right">Payment method</TD>
1212 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1225 'amount' => sprintf('%.2f', $cust_pay->paid),
1226 'date' => $cust_pay->_date,
1227 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1228 'time_pretty' => time2str('%T', $cust_pay->_date),
1229 'auth_num' => $cust_pay->auth,
1230 'order_num' => $cust_pay->order_number,
1231 'receipt_html' => $receipt_html,
1238 'receipt_html' => '',
1245 sub realtime_collect {
1248 my $session = _cache->get($p->{'session_id'})
1249 or return { 'error' => "Can't resume session" }; #better error message
1251 my $custnum = $session->{'custnum'};
1253 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1254 or return { 'error' => "unknown custnum $custnum" };
1257 if ( $p->{'amount'} ) {
1258 $amount = $p->{'amount'};
1260 elsif ( $session->{'pkgnum'} ) {
1261 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1264 $amount = $cust_main->balance;
1267 my $error = $cust_main->realtime_collect(
1268 'method' => $p->{'method'},
1269 'amount' => $amount,
1270 'pkgnum' => $session->{'pkgnum'},
1271 'session_id' => $p->{'session_id'},
1275 return { 'error' => $error } unless ref( $error );
1277 return { 'error' => '', amount => $amount, %$error };
1280 sub start_thirdparty {
1282 my $session = _cache->get($p->{'session_id'})
1283 or return { 'error' => "Can't resume session" }; #better error message
1284 my $custnum = $session->{'custnum'};
1285 my $cust_main = FS::cust_main->by_key($custnum);
1287 my $amount = $p->{'amount'}
1288 or return { error => 'no amount' };
1290 my $result = $cust_main->create_payment(
1291 'method' => $p->{'method'},
1292 'amount' => $p->{'amount'},
1293 'pkgnum' => $session->{'pkgnum'},
1294 'session_id' => $p->{'session_id'},
1297 if ( ref($result) ) { # hashref or error
1300 return { error => $result };
1304 sub finish_thirdparty {
1306 my $session_id = delete $p->{'session_id'};
1307 my $session = _cache->get($session_id)
1308 or return { 'error' => "Can't resume session" };
1309 my $custnum = $session->{'custnum'};
1310 my $cust_main = FS::cust_main->by_key($custnum);
1312 if ( $p->{_cancel} ) {
1313 # customer backed out of making a payment
1314 return $cust_main->cancel_payment( $session_id );
1316 my $result = $cust_main->execute_payment( $session_id, %$p );
1317 if ( ref($result) ) {
1320 return { error => $result };
1324 sub process_payment_order_pkg {
1327 my $hr = process_payment($p);
1328 return $hr if $hr->{'error'};
1333 sub process_payment_order_renew {
1336 my $hr = process_payment($p);
1337 return $hr if $hr->{'error'};
1342 sub process_prepay {
1346 my $session = _cache->get($p->{'session_id'})
1347 or return { 'error' => "Can't resume session" }; #better error message
1351 my $custnum = $session->{'custnum'};
1353 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1354 or return { 'error' => "unknown custnum $custnum" };
1356 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1357 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1365 return { 'error' => $error } if $error;
1367 return { 'error' => '',
1368 'amount' => $amount,
1369 'seconds' => $seconds,
1370 'duration' => duration_exact($seconds),
1371 'upbytes' => $upbytes,
1372 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1373 'downbytes' => $downbytes,
1374 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1375 'totalbytes'=> $totalbytes,
1376 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1383 my $session = _cache->get($p->{'session_id'})
1384 or return { 'error' => "Can't resume session" }; #better error message
1386 my $custnum = $session->{'custnum'};
1388 my $invnum = $p->{'invnum'};
1390 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1391 'custnum' => $custnum } )
1392 or return { 'error' => "Can't find invnum" };
1396 return { 'error' => '',
1397 'invnum' => $invnum,
1398 'invoice_text' => join('', $cust_bill->print_text ),
1399 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1406 my $session = _cache->get($p->{'session_id'})
1407 or return { 'error' => "Can't resume session" }; #better error message
1409 my $custnum = $session->{'custnum'};
1411 my $invnum = $p->{'invnum'};
1413 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1414 'custnum' => $custnum } )
1415 or return { 'error' => "Can't find invnum" };
1419 return { 'error' => '',
1420 'invnum' => $invnum,
1421 'invoice_pdf' => $cust_bill->print_pdf({
1422 'unsquelch_cdr' => 1,
1423 'locale' => $p->{'locale'},
1429 sub legacy_invoice {
1431 my $session = _cache->get($p->{'session_id'})
1432 or return { 'error' => "Can't resume session" }; #better error message
1434 my $custnum = $session->{'custnum'};
1436 my $legacyinvnum = $p->{'legacyinvnum'};
1439 'legacyinvnum' => $legacyinvnum,
1440 'custnum' => $custnum,
1443 my $legacy_cust_bill =
1444 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1445 || qsearchs('legacy_cust_bill', \%hash )
1446 or return { 'error' => "Can't find legacyinvnum" };
1450 return { 'error' => '',
1451 'legacyinvnum' => $legacyinvnum,
1452 'legacyid' => $legacy_cust_bill->legacyid,
1453 'invoice_html' => $legacy_cust_bill->content_html,
1458 sub legacy_invoice_pdf {
1460 my $session = _cache->get($p->{'session_id'})
1461 or return { 'error' => "Can't resume session" }; #better error message
1463 my $custnum = $session->{'custnum'};
1465 my $legacyinvnum = $p->{'legacyinvnum'};
1467 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1468 'legacyinvnum' => $legacyinvnum,
1469 'custnum' => $custnum,
1470 }) or return { 'error' => "Can't find legacyinvnum" };
1474 return { 'error' => '',
1475 'legacyinvnum' => $legacyinvnum,
1476 'legacyid' => $legacy_cust_bill->legacyid,
1477 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1485 #sessioning for this? how do we get the session id to the backend invoice
1486 # template so it can add it to the link, blah
1489 if ( $p->{'invnum'} ) {
1490 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1491 or return { 'error' => 'unknown invnum' };
1492 $agentnum = $cust_bill->cust_main->agentnum;
1495 my $templatename = $p->{'template'} || $p->{'templatename'};
1497 #false laziness-ish w/view/cust_bill-logo.cgi
1499 my $conf = new FS::Conf;
1500 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1501 $templatename = "_$1";
1506 my $filename = "logo$templatename.png";
1508 return { 'error' => '',
1509 'logo' => $conf->config_binary($filename, $agentnum),
1510 'content_type' => 'image/png', #should allow gif, jpg too
1516 my $session = _cache->get($p->{'session_id'})
1517 or return { 'error' => "Can't resume session" }; #better error message
1519 my $custnum = $session->{'custnum'};
1521 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1522 or return { 'error' => "unknown custnum $custnum" };
1524 my $conf = new FS::Conf;
1526 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1528 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1533 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1534 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1535 my $owed = $_->owed;
1537 +{ 'invnum' => $_->invnum,
1538 '_date' => $_->_date,
1539 'date' => time2str("%b %o, %Y", $_->_date),
1540 'date_short' => time2str("%m-%d-%Y", $_->_date),
1541 'previous' => sprintf('%.2f', ($_->previous)[0]),
1542 'charged' => sprintf('%.2f', $_->charged),
1543 'owed' => sprintf('%.2f', $owed),
1544 'balance' => sprintf('%.2f', $balance),
1545 'lastpay' => @payments_and_credits
1546 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1552 return { 'error' => '',
1553 'balance' => $cust_main->balance,
1554 'money_char' => $conf->config("money_char") || '$',
1555 'invoices' => $invoices,
1556 'legacy_invoices' => [
1558 +{ 'legacyinvnum' => $_->legacyinvnum,
1559 'legacyid' => $_->legacyid,
1560 '_date' => $_->_date,
1561 'date' => time2str("%b %o, %Y", $_->_date),
1562 'date_short' => time2str("%m-%d-%Y", $_->_date),
1563 'charged' => sprintf('%.2f', $_->charged),
1564 'has_content' => ( length($_->content_pdf)
1565 || length($_->content_html) ),
1576 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1577 return { 'error' => $session } if $context eq 'error';
1579 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1580 or return { 'error' => "unknown custnum $custnum" };
1584 my $cust_payby = $_;
1586 map { $_ => $cust_payby->$_ }
1587 qw( custpaybynum weight payby paymask paydate
1588 payname paystate paytype
1592 $cust_main->cust_payby
1600 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1601 return { 'error' => $session } if $context eq 'error';
1603 #XXX payinfo1 + payinfo2 for CHEK?
1604 #or take the opportunity to use separate, more well- named fields?
1606 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1607 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1608 # my $payinfo1 = $1;
1609 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1610 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1611 # my $payinfo2 = $1;
1612 # $payinfo = $payinfo1. '@'. $payinfo2;
1614 my $cust_payby = new FS::cust_payby {
1615 'custnum' => $custnum,
1616 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1617 paystate paytype payip
1621 my $error = $cust_payby->insert;
1623 return { 'error' => $error };
1625 return { 'custpaybynum' => $cust_payby->custpaybynum };
1633 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1634 return { 'error' => $session } if $context eq 'error';
1636 my $cust_payby = qsearchs('cust_payby', {
1637 'custnum' => $custnum,
1638 'custpaybynum' => $p->{'custpaybynum'},
1640 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1642 return { 'error' => $cust_payby->delete };
1648 my $session = _cache->get($p->{'session_id'})
1649 or return { 'error' => "Can't resume session" }; #better error message
1651 my $custnum = $session->{'custnum'};
1653 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1654 or return { 'error' => "unknown custnum $custnum" };
1656 my @errors = $cust_main->cancel( 'quiet'=>1 );
1658 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1660 return { 'error' => $error };
1667 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1668 return { 'error' => $session } if $context eq 'error';
1670 my $search = { 'custnum' => $custnum };
1671 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1672 my $cust_main = qsearchs('cust_main', $search )
1673 or return { 'error' => "unknown custnum $custnum" };
1675 my $conf = new FS::Conf;
1676 my $immutable = $conf->exists('selfservice_immutable-package');
1678 # the duplication below is necessary:
1679 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1680 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1681 # non-backwards-compatible change breaking the software of anyone using the API
1682 # instead of the stock selfservice
1683 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1684 if( $conf->exists('selfservice_server-view-wholesale') ) {
1685 return { 'svcnum' => $session->{'svcnum'},
1686 'custnum' => $custnum,
1687 'cust_pkg' => [ map {
1689 immutable => $immutable,
1690 part_pkg => [ map $_->hashref, $_->part_pkg ],
1692 [ map $_->hashref, $_->available_part_svc ],
1694 [ map { my $ref = { $_->hash,
1695 label => [ $_->label ],
1697 $ref->{_password} = $_->svc_x->_password
1698 if $context eq 'agent'
1699 && $conf->exists('agent-showpasswords')
1700 && $_->part_svc->svcdb eq 'svc_acct';
1705 } $cust_main->cust_pkg
1708 small_custview( $cust_main, $conf->config('countrydefault') ),
1709 'wholesale_view' => 1,
1710 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1711 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1712 'lnp' => $conf->exists('svc_phone-lnp'),
1716 { 'svcnum' => $session->{'svcnum'},
1717 'custnum' => $custnum,
1718 'cust_pkg' => [ map {
1719 my $primary_cust_svc = $_->primary_cust_svc;
1722 immutable => $immutable,
1723 pkg_label => $_->pkg_locale,
1724 status => $_->status,
1725 statuscolor => $_->statuscolor,
1727 [ map { $_->hashref }
1728 grep { $_->selfservice_access ne 'hidden' }
1729 $_->available_part_svc
1732 [ map { my $ref = { $_->hash,
1733 label => [ $_->label ],
1735 $ref->{_password} = $_->svc_x->_password
1736 if $context eq 'agent'
1737 && $conf->exists('agent-showpasswords')
1738 && $_->part_svc->svcdb eq 'svc_acct';
1739 $ref->{svchash} = { $_->svc_x->hash } if
1740 $_->part_svc->svcdb eq 'svc_phone';
1741 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1742 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1745 grep { $_->part_svc->selfservice_access ne 'hidden' }
1750 ? { $primary_cust_svc->hash,
1751 label => [ $primary_cust_svc->label ],
1752 finger => $primary_cust_svc->svc_x->finger, #uuh
1753 $primary_cust_svc->part_svc->hash,
1757 } $cust_main->ncancelled_pkgs
1760 small_custview( $cust_main, $conf->config('countrydefault') ),
1761 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1769 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1770 return { 'error' => $session } if $context eq 'error';
1772 my $conf = new FS::Conf;
1774 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1775 my $search = { 'custnum' => $custnum };
1776 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1777 my $cust_main = qsearchs('cust_main', $search )
1778 or return { 'error' => "unknown custnum $custnum" };
1780 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1781 if ( ! $pkgnum && $p->{'svcnum'} ) {
1782 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1783 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1787 my @cust_pkg_usage = ();
1788 foreach my $cust_pkg ( $p->{'ncancelled'}
1789 ? $cust_main->ncancelled_pkgs
1790 : $cust_main->unsuspended_pkgs ) {
1791 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1792 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1793 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1796 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1799 foreach (@cust_pkg_usage) {
1800 my $part = $_->part_pkg_usage;
1801 my $tag = $part->description . ($part->shared ? 1 : 0);
1802 my $row = $usage_pools{$tag}
1803 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1804 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1805 $row->[2] += $part->minutes; # minutes total
1807 } # otherwise just leave them empty
1809 if ( $p->{'svcdb'} ) {
1810 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1812 : ref($p->{'svcdb'}) eq 'ARRAY'
1813 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1814 : { $p->{'svcdb'} => 1 };
1815 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1818 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1821 my @svcs; # stuff to return to the client
1822 foreach my $cust_svc (@cust_svc) {
1823 my $svc_x = $cust_svc->svc_x;
1824 my($label, $value) = $cust_svc->label;
1825 my $part_svc = $cust_svc->part_svc;
1826 my $svcdb = $part_svc->svcdb;
1827 my $cust_pkg = $cust_svc->cust_pkg;
1828 my $part_pkg = $cust_pkg->part_pkg;
1831 'svcnum' => $cust_svc->svcnum,
1832 'display_svcnum' => $cust_svc->display_svcnum,
1836 'pkg_label' => $cust_pkg->pkg_locale,
1837 'pkg_status' => $cust_pkg->status,
1838 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1841 # would it make sense to put this in a svc_* method?
1843 if ( $svcdb eq 'svc_acct' ) {
1844 foreach (qw(username email finger seconds)) {
1845 $hash{$_} = $svc_x->$_;
1851 'upbytes' => display_bytecount($svc_x->upbytes),
1852 'downbytes' => display_bytecount($svc_x->downbytes),
1853 'totalbytes' => display_bytecount($svc_x->totalbytes),
1855 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1856 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1857 'recharge_upbytes' =>
1858 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1859 'recharge_downbytes' =>
1860 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1861 'recharge_totalbytes' =>
1862 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1867 } elsif ( $svcdb eq 'svc_dsl' ) {
1869 $hash{'phonenum'} = $svc_x->phonenum;
1870 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1871 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1872 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1875 $hash{'name'} = $cust_main->name;
1877 # no usage to hide here
1879 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1881 # could potentially show lots of things...
1882 $hash{'outbound'} = 1;
1883 $hash{'inbound'} = 0;
1884 if ( $svcdb eq 'svc_phone' ) {
1885 if ( $part_pkg->plan eq 'voip_inbound' ) {
1886 $hash{'outbound'} = 0;
1887 $hash{'inbound'} = 1;
1888 } elsif ( $part_pkg->option('selfservice_inbound_format')
1889 or $conf->config('selfservice-default_inbound_cdr_format')
1891 $hash{'inbound'} = 1;
1894 foreach (qw(inbound outbound)) {
1895 # hmm...we can't filter by status here, because there might
1896 # not be cdr_terminations at all. have to go by date.
1897 # find all since the last bill date.
1898 # XXX cdr types? we are going to need them.
1900 my $sum_cdr = $svc_x->sum_cdrs(
1901 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1902 'begin' => ($cust_pkg->last_bill || 0),
1904 'disable_charged_party' => 1,
1906 $hash{$_} = $sum_cdr->hashref;
1909 } # not hiding usage
1913 } # foreach $cust_svc
1916 'svcnum' => $session->{'svcnum'},
1917 'custnum' => $custnum,
1918 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1919 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1922 map { $usage_pools{$_} }
1926 'hide_usage' => $hide_usage,
1931 sub _customer_svc_x {
1932 my($custnum, $svcnum, $table) = (shift, shift, shift);
1933 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1935 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1936 my $search = " AND custnum = $1";
1937 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1940 'table' => ($table || 'svc_acct'),
1941 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1942 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1943 #'LEFT JOIN cust_main USING ( custnum ) ',
1944 'hashref' => $hashref,
1945 'extra_sql' => $search, #important
1950 sub svc_status_html {
1953 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1954 return { 'error' => $session } if $context eq 'error';
1956 #XXX only svc_dsl for now
1957 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1958 or return { 'error' => "Service not found" };
1960 my $html = $svc_x->getstatus_html;
1962 return { 'html' => $html };
1966 sub svc_status_hash {
1969 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1970 return { 'error' => $session } if $context eq 'error';
1972 #XXX only svc_acct for now
1973 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1974 or return { 'error' => "Service not found" };
1976 my ( $html, $hashref ) = $svc_x->export_getstatus;
1981 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1982 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1983 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1984 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1985 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1988 my( $p, $method ) = @_;
1990 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1991 return { 'error' => $session } if $context eq 'error';
1993 #XXX only svc_acct for now
1994 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1995 or return { 'error' => "Service not found" };
1997 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1999 my $error = $svc_x->$method($p); #$p? returns error?
2000 return { 'error' => $error } if $error;
2002 return {}; #? { 'error' => '' }
2006 sub acct_forward_info {
2009 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2010 return { 'error' => $session } if $context eq 'error';
2012 my $svc_forward = _customer_svc_x( $custnum,
2013 { 'srcsvc' => $p->{'svcnum'} },
2016 or return { 'error' => '',
2020 return { 'error' => '',
2021 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2026 sub process_acct_forward {
2028 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2029 return { 'error' => $session } if $context eq 'error';
2031 my $old = _customer_svc_x( $custnum,
2032 { 'srcsvc' => $p->{'svcnum'} },
2036 if ( $p->{'dst'} eq '' ) {
2038 my $error = $old->delete;
2039 return { 'error' => $error };
2041 return { 'error' => '' };
2044 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2045 'dst' => $p->{'dst'},
2050 $new->svcnum($old->svcnum);
2051 my $cust_svc = $old->cust_svc;
2052 $new->svcpart($old->svcpart);
2053 $new->pkgnuym($old->pkgnum);
2054 $error = $new->replace($old);
2056 my $conf = new FS::Conf;
2057 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2059 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2060 or return { 'error' => 'No service' }; #how would we even get here?
2062 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2064 $error = $new->insert;
2067 return { 'error' => $error };
2071 sub list_dsl_devices {
2074 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2075 return { 'error' => $session } if $context eq 'error';
2077 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2078 or return { 'error' => "Service not found" };
2081 'devices' => [ map {
2082 +{ 'mac_addr' => $_->mac_addr };
2083 } $svc_dsl->dsl_device
2089 sub add_dsl_device {
2092 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2093 return { 'error' => $session } if $context eq 'error';
2095 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2096 or return { 'error' => "Service not found" };
2098 return { 'error' => 'No MAC address supplied' }
2099 unless length($p->{'mac_addr'});
2101 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2102 'mac_addr' => scalar($p->{'mac_addr'}),
2104 my $error = $dsl_device->insert;
2105 return { 'error' => $error };
2109 sub delete_dsl_device {
2112 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2113 return { 'error' => $session } if $context eq 'error';
2115 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2116 or return { 'error' => "Service not found" };
2118 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2119 'mac_addr' => scalar($p->{'mac_addr'}),
2122 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2124 my $error = $dsl_device->delete;
2125 return { 'error' => $error };
2131 _usage_details( \&_port_graph, $p,
2132 'svcdb' => 'svc_port',
2137 my($svc_port, $begin, $end) = @_;
2139 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2140 push @usage, { 'png' => $pngOrError };
2144 sub _list_svc_usage {
2145 my($svc_acct, $begin, $end) = @_;
2147 foreach my $part_export (
2148 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2149 qw( sqlradius sqlradius_withdomain )
2151 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2156 sub list_svc_usage {
2157 _usage_details(\&_list_svc_usage, @_);
2160 sub _list_support_usage {
2161 my($svc_acct, $begin, $end) = @_;
2163 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2164 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2166 push @usage, { 'seconds' => $_->seconds,
2167 'support' => $_->support,
2168 '_date' => $_->_date,
2169 'id' => $_->transaction_id,
2170 'creator' => $_->creator,
2171 'subject' => $_->subject,
2172 'status' => $_->status,
2173 'ticketid' => $_->ticketid,
2179 sub list_support_usage {
2180 _usage_details(\&_list_support_usage, @_);
2183 sub _list_cdr_usage {
2184 # XXX CDR type support...
2185 # XXX any way to do a paged search on this?
2186 # we have to return the results all at once...
2187 my($svc_x, $begin, $end, %opt) = @_;
2188 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2192 'disable_charged_party' => 1,
2197 sub list_cdr_usage {
2199 _usage_details( \&_list_cdr_usage, $p );
2202 sub _usage_details {
2203 my($callback, $p, %opt) = @_;
2204 my $conf = FS::Conf->new;
2206 if ( $conf->exists('selfservice_hide-usage') ) {
2207 return { 'error' => 'Viewing usage is not allowed.' };
2210 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2211 return { 'error' => $session } if $context eq 'error';
2213 my $search = { 'svcnum' => $p->{'svcnum'} };
2214 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2216 my $cust_svc = qsearchs( 'cust_svc', $search );
2217 return { 'error' => 'No service selected in list_svc_usage' }
2220 my $svc_x = $cust_svc->svc_x;
2221 my $svcdb = $svc_x->table;
2222 my $cust_pkg = $cust_svc->cust_pkg;
2223 my $freq = $cust_pkg->part_pkg->freq;
2226 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2228 if ( $p->{inbound} ) {
2229 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2230 || $conf->config('selfservice-default_inbound_cdr_format')
2231 || 'source_default';
2232 $callback_opt{inbound} = 1;
2234 $format = $cust_pkg->part_pkg->option('selfservice_format')
2235 || $conf->config('selfservice-default_cdr_format')
2239 $callback_opt{format} = $format;
2240 $callback_opt{use_clid} = 1;
2241 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2244 my $start = $cust_pkg->setup;
2245 #my $end = $cust_pkg->bill; # or time?
2248 unless ( $p->{beginning} ) {
2249 $p->{beginning} = $cust_pkg->last_bill;
2250 $p->{ending} = $end;
2253 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2254 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2256 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2260 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2261 # ugly kludge, I know
2262 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2263 if (defined $delete_col) {
2264 delete($_->[$delete_col]) foreach ($header, @usage);
2268 #kinda false laziness with FS::cust_main::bill, but perhaps
2269 #we should really change this bit to DateTime and DateTime::Duration
2271 #change this bit to use Date::Manip? CAREFUL with timezones (see
2272 # mailing list archive)
2273 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2274 (localtime($p->{ending}) )[0,1,2,3,4,5];
2275 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2276 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2278 if ( $freq =~ /^\d+$/ ) {
2280 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2282 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2283 } elsif ( $freq =~ /^(\d+)w$/ ) {
2285 $nmday += $weeks * 7;
2286 $pmday -= $weeks * 7;
2287 } elsif ( $freq =~ /^(\d+)d$/ ) {
2291 } elsif ( $freq =~ /^(\d+)h$/ ) {
2296 return { 'error' => "unparsable frequency: ". $freq };
2299 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2300 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2304 'svcnum' => $p->{svcnum},
2305 'beginning' => $p->{beginning},
2306 'ending' => $p->{ending},
2307 'inbound' => $p->{inbound},
2308 'previous' => ($previous > $start) ? $previous : $start,
2309 'next' => ($next < $end) ? $next : $end,
2310 'header' => $header,
2318 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2319 return { 'error' => $session } if $context eq 'error';
2321 my $search = { 'custnum' => $custnum };
2322 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2323 my $cust_main = qsearchs('cust_main', $search )
2324 or return { 'error' => "unknown custnum $custnum" };
2326 my $status = $cust_main->status;
2328 my %order_pkg_options = ();
2329 if ( $p->{locationnum} > 0 ) {
2330 $order_pkg_options{locationnum} = delete($p->{locationnum});
2331 } elsif ( $p->{address1} ) {
2332 $order_pkg_options{'cust_location'} = new FS::cust_location {
2333 map { $_ => $p->{$_} }
2334 qw( address1 address2 city county state zip country )
2338 #false laziness w/ClientAPI/Signup.pm
2340 my $cust_pkg = new FS::cust_pkg ( {
2341 'custnum' => $custnum,
2342 'pkgpart' => $p->{'pkgpart'},
2343 'quantity' => $p->{'quantity'} || 1,
2345 my $error = $cust_pkg->check;
2346 return { 'error' => $error } if $error;
2349 unless ( $p->{'svcpart'} eq 'none' ) {
2353 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2355 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2356 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2357 $svcdb = $part_svc->svcdb;
2359 $svcdb = 'svc_acct';
2361 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2364 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2365 'svc_domain' => [ qw( domain ) ],
2366 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2367 'svc_external' => [ qw( id title ) ],
2368 'svc_pbx' => [ qw( id title ) ],
2371 my $svc_x = "FS::$svcdb"->new( {
2372 'svcpart' => $svcpart,
2373 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2376 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2379 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2380 my $acct_snarf = new FS::acct_snarf ( {
2381 'machine' => $p->{"snarf_machine$snarfnum"},
2382 'protocol' => $p->{"snarf_protocol$snarfnum"},
2383 'username' => $p->{"snarf_username$snarfnum"},
2384 '_password' => $p->{"snarf_password$snarfnum"},
2387 push @acct_snarf, $acct_snarf;
2389 $svc_x->child_objects( \@acct_snarf );
2392 my $y = $svc_x->setdefault; # arguably should be in new method
2393 return { 'error' => $y } if $y && !ref($y);
2395 $error = $svc_x->check;
2396 return { 'error' => $error } if $error;
2402 $error = $cust_main->order_pkg(
2403 'cust_pkg' => $cust_pkg,
2408 return { 'error' => $error } if $error;
2410 my $conf = new FS::Conf;
2411 if ( $conf->exists('signup_server-realtime') ) {
2413 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2416 $cust_pkg->cancel('quiet'=>1);
2419 $cust_pkg->reexport;
2423 $cust_pkg->reexport;
2426 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2428 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2435 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2436 return { 'error' => $session } if $context eq 'error';
2438 my $conf = new FS::Conf;
2439 my $immutable = $conf->exists('selfservice_immutable-package');
2440 return { 'error' => "Package modification disabled" } if $immutable;
2442 my $search = { 'custnum' => $custnum };
2443 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2444 my $cust_main = qsearchs('cust_main', $search )
2445 or return { 'error' => "unknown custnum $custnum" };
2447 my $status = $cust_main->status;
2448 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2449 or return { 'error' => "unknown package $p->{pkgnum}" };
2451 #if someone does need self-service package change of suspended packages,
2452 # figure out how to be more discriminating
2453 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2454 if $cust_pkg->status eq 'suspended';
2456 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2457 'quantity' => $p->{'quantity'} || 1,
2460 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2461 unless ref($err_or_cust_pkg);
2463 if ( $conf->exists('signup_server-realtime') ) {
2465 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2468 $err_or_cust_pkg->suspend;
2471 $err_or_cust_pkg->reexport;
2475 $err_or_cust_pkg->reexport;
2478 return { error => '', pkgnum => $cust_pkg->pkgnum };
2482 sub order_recharge {
2485 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2486 return { 'error' => $session } if $context eq 'error';
2488 my $search = { 'custnum' => $custnum };
2489 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2490 my $cust_main = qsearchs('cust_main', $search )
2491 or return { 'error' => "unknown custnum $custnum" };
2493 my $status = $cust_main->status;
2494 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2495 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2497 my $svc_x = $cust_svc->svc_x;
2498 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2501 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2502 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2503 recharge_totalbytes );
2504 my $amount = $part_pkg->option('recharge_amount', 1);
2506 my ($l, $v, $d) = $cust_svc->label; # blah
2507 my $pkg = "Recharge $v";
2509 my $bill_error = $cust_main->charge($amount, $pkg,
2510 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2511 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2512 $part_pkg->taxclass); #meh
2514 my $conf = new FS::Conf;
2515 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2517 $bill_error = _do_bop_realtime( $cust_main, $status );
2522 my $error = $svc_x->recharge (\%vhash);
2523 return { 'error' => $error } if $error;
2527 my $error = $bill_error;
2528 $error ||= $svc_x->recharge (\%vhash);
2529 return { 'error' => $error } if $error;
2532 return { error => '', svc => $cust_svc->part_svc->svc };
2536 sub _do_bop_realtime {
2537 my ($cust_main, $status, %opt) = @_;
2539 my $old_balance = $cust_main->balance;
2542 my $bill_error = $cust_main->bill(
2543 'return_bill' => \@cust_bill,
2546 $bill_error ||= $cust_main->apply_payments_and_credits;
2548 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2550 if ( $cust_main->balance > $old_balance
2551 && $cust_main->balance > 0
2552 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2555 unless ( $opt{'no_invoice_void'} ) {
2557 #this used to apply a credit, but now we can void invoices...
2558 foreach my $cust_bill (@cust_bill) {
2559 my $voiderror = $cust_bill->void('automatic payment failed');
2560 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2565 return { 'error' => '_decline', 'bill_error' => $bill_error };
2568 if ( $opt{'collect'} ) {
2569 my $collect_error = $cust_main->collect();
2570 return { 'error' => '_decline', 'bill_error' => $collect_error }
2571 if $collect_error; #?
2580 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2581 return { 'error' => $session } if $context eq 'error';
2583 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2584 or return { 'error' => "unknown custnum $custnum" };
2586 my @cust_pkg = sort { $a->bill <=> $b->bill }
2587 grep { $_->part_pkg->freq ne '0' }
2588 $cust_main->ncancelled_pkgs;
2590 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2592 my $total = $cust_main->balance;
2595 my $bill = $_->bill;
2596 $total += $_->part_pkg->base_recur($_, \$bill);
2597 my $renew_date = $_->part_pkg->add_freq($_->bill);
2599 'pkgnum' => $_->pkgnum,
2600 'amount' => sprintf('%.2f', $total),
2601 'bill_date' => $_->bill,
2602 'bill_date_pretty' => time2str('%x', $_->bill),
2603 'renew_date' => $renew_date,
2604 'renew_date_pretty' => time2str('%x', $renew_date),
2605 'expire_date' => $_->expire,
2606 'expire_date_pretty' => time2str('%x', $_->expire),
2611 return { 'dates' => \@array };
2615 sub payment_info_renew_info {
2617 my $renew_info = renew_info($p);
2618 my $payment_info = payment_info($p);
2619 return { %$renew_info,
2627 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2628 return { 'error' => $session } if $context eq 'error';
2630 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2631 or return { 'error' => "unknown custnum $custnum" };
2633 my $date = $p->{'date'};
2637 #freeside-daily -n -d $date fs_daily $custnum
2638 $cust_main->bill_and_collect( 'time' => $date,
2639 'invoice_time' => $now,
2640 'actual_time' => $now,
2641 'check_freq' => '1d',
2644 return { 'error' => '' };
2650 my $session = _cache->get($p->{'session_id'})
2651 or return { 'error' => "Can't resume session" }; #better error message
2653 my $custnum = $session->{'custnum'};
2655 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2656 or return { 'error' => "unknown custnum $custnum" };
2658 my $conf = new FS::Conf;
2660 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2661 or return { 'error' => 'Permission denied' };
2663 my $pkgnum = $p->{'pkgnum'};
2665 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2666 'pkgnum' => $pkgnum, } )
2667 or return { 'error' => "unknown pkgnum $pkgnum" };
2669 my $error = $cust_pkg->suspend(reason => $reasonnum);
2670 return { 'error' => $error };
2676 my $session = _cache->get($p->{'session_id'})
2677 or return { 'error' => "Can't resume session" }; #better error message
2679 my $custnum = $session->{'custnum'};
2680 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2681 or return { 'error' => "unknown custnum $custnum" };
2683 my $pkgnum = $p->{'pkgnum'};
2684 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2685 'pkgnum' => $pkgnum, } )
2686 or return { 'error' => "unknown pkgnum $pkgnum" };
2688 my $error = $cust_pkg->cancel( 'quiet' => 1,
2689 'date' => $p->{'date'},
2691 return { 'error' => $error };
2694 sub provision_phone {
2697 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2699 #editing an existing phone number
2700 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2701 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2702 return { 'error' => $session } if $context eq 'error';
2704 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2705 return { 'error' => 'service not found' } unless $svc_phone;
2706 return { 'error' => 'invalid svcnum' }
2707 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2709 $svc_phone->email($p->{'email'})
2710 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2711 $svc_phone->forwarddst($p->{'forwarddst'})
2712 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2713 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2714 return { 'error' => $svc_phone->replace };
2718 unless ( $p->{'lnp'} ) {
2719 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2720 $p->{'lnp_status'} = "portingin";
2721 return _provision( 'FS::svc_phone',
2722 [qw(lnp_desired_due_date lnp_other_provider
2723 lnp_other_provider_account phonenum countrycode lnp_status)],
2724 [qw(phonenum countrycode)],
2730 # single DID order (the usual case)
2731 unless (scalar(@bulkdid)) {
2732 return _provision( 'FS::svc_phone',
2733 [qw(phonenum countrycode)],
2734 [qw(phonenum countrycode)],
2740 # bulk DID order case
2742 foreach my $did ( @bulkdid ) {
2743 $did =~ s/[^0-9]//g;
2744 $error = _provision( 'FS::svc_phone',
2745 [qw(phonenum countrycode)],
2746 [qw(phonenum countrycode)],
2748 'pkgnum' => $p->{'pkgnum'},
2749 'svcpart' => $p->{'svcpart'},
2751 'countrycode' => $p->{'countrycode'},
2752 'session_id' => $p->{'session_id'},
2755 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2757 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2762 warn "provision_pbx called\n"
2765 warn "provision_pbx calling _provision\n"
2767 _provision( 'FS::svc_pbx',
2768 [qw(id title max_extensions max_simultaneous ip_addr)],
2769 [qw(id title max_extensions max_simultaneous ip_addr)],
2775 sub provision_acct {
2777 warn "provision_acct called\n"
2780 return { 'error' => gettext('passwords_dont_match') }
2781 if $p->{'_password'} ne $p->{'_password2'};
2782 return { 'error' => gettext('empty_password') }
2783 unless length($p->{'_password'});
2785 if ($p->{'domsvc'}) {
2786 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2787 qw ( svcpart pkgnum ) );
2788 return { 'error' => gettext('invalid_domain') }
2789 unless ($domains{$p->{'domsvc'}});
2792 warn "provision_acct calling _provision\n"
2794 _provision( 'FS::svc_acct',
2795 [qw(username _password domsvc)],
2796 [qw(username _password domsvc)],
2802 sub provision_external {
2804 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2805 _provision( 'FS::svc_external',
2813 sub provision_forward {
2815 _provision( 'FS::svc_forward',
2816 ['srcsvc','src','dstsvc','dst'],
2823 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2824 warn "_provision called for $class\n"
2827 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2828 return { 'error' => $session } if $context eq 'error';
2830 my $search = { 'custnum' => $custnum };
2831 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2832 my $cust_main = qsearchs('cust_main', $search )
2833 or return { 'error' => "unknown custnum $custnum" };
2835 my $pkgnum = $p->{'pkgnum'};
2837 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2839 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2840 'pkgnum' => $pkgnum,
2842 or return { 'error' => "unknown pkgnum $pkgnum" };
2844 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2846 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2847 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2849 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2850 if $class ne 'FS::'. $part_svc->svcdb;
2852 warn "creating $class record\n"
2854 my $svc_x = $class->new( {
2855 'pkgnum' => $p->{'pkgnum'},
2856 'svcpart' => $p->{'svcpart'},
2857 map { $_ => $p->{$_} } @$fields
2860 my %insert_args = ();
2861 #i shouldn't be a special case here (pass an option or something)
2862 if ( $class eq 'FS::svc_phone'
2863 && grep length($p->{$_}), @location_editable_fields
2866 $insert_args{'cust_location'} = new FS::cust_location {
2867 map { $_ => $p->{$_} } @location_editable_fields
2871 warn "inserting $class record\n"
2873 my $error = $svc_x->insert(%insert_args);
2876 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2878 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2881 my $return = { 'svc' => $part_svc->svc,
2883 map { $_ => $svc_x->get($_) } @$return_fields
2885 warn "_provision returning ". Dumper($return). "\n"
2894 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2895 return { 'error' => $session } if $context eq 'error';
2897 my $search = { 'custnum' => $custnum };
2898 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2899 my $cust_main = qsearchs('cust_main', $search )
2900 or return { 'error' => "unknown custnum $custnum" };
2902 my $pkgnum = $p->{'pkgnum'};
2904 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2905 'pkgnum' => $pkgnum,
2907 or return { 'error' => "unknown pkgnum $pkgnum" };
2909 my $svcpart = $p->{'svcpart'};
2911 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2912 'svcpart' => $svcpart, } )
2913 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2914 my $part_svc = $pkg_svc->part_svc;
2916 my $conf = new FS::Conf;
2919 'svc' => $part_svc->svc,
2920 'svcdb' => $part_svc->svcdb,
2921 'pkgnum' => $pkgnum,
2922 'svcpart' => $svcpart,
2923 'custnum' => $custnum,
2925 'security_phrase' => 0, #XXX !
2926 'svc_acct_pop' => [], #XXX !
2928 'init_popstate' => '',
2933 small_custview( $cust_main, $conf->config('countrydefault') ),
2937 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2938 && $ret->{'svcdb'} eq 'svc_phone') {
2939 $ret->{'svcnum'} = $p->{'svcnum'};
2940 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2941 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2942 $ret->{'email'} = $svc_phone->email;
2943 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2947 if ($ret->{'svcdb'} eq 'svc_forward') {
2948 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2954 sub unprovision_svc {
2957 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2958 return { 'error' => $session } if $context eq 'error';
2960 my $search = { 'custnum' => $custnum };
2961 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2962 my $cust_main = qsearchs('cust_main', $search )
2963 or return { 'error' => "unknown custnum $custnum" };
2965 my $svcnum = $p->{'svcnum'};
2967 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2968 or return { 'error' => "unknown svcnum $svcnum" };
2970 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2971 unless $cust_svc->cust_pkg->custnum == $custnum;
2973 my $conf = new FS::Conf;
2975 return { 'svc' => $cust_svc->part_svc->svc,
2976 'error' => $cust_svc->cancel,
2978 small_custview( $cust_main, $conf->config('countrydefault') ),
2983 sub myaccount_passwd {
2985 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2986 return { 'error' => $session } if $context eq 'error';
2988 return { 'error' => "New passwords don't match." }
2989 if $p->{'new_password'} ne $p->{'new_password2'};
2991 return { 'error' => 'Enter new password' }
2992 unless length($p->{'new_password'});
2994 #my $search = { 'custnum' => $custnum };
2995 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2996 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2997 my $search = " AND custnum = $1";
2998 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3000 my $svc_acct = qsearchs( {
3001 'table' => 'svc_acct',
3002 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3003 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3004 'LEFT JOIN cust_main USING ( custnum ) ',
3005 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3006 'extra_sql' => $search, #important
3008 or return { 'error' => "Service not found" };
3012 my $conf = new FS::Conf;
3014 return { 'error' => 'Incorrect current password.' }
3015 if ( exists($p->{'old_password'})
3016 || $conf->exists('selfservice-password_change_oldpass')
3018 && ! $svc_acct->check_password($p->{'old_password'});
3020 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3021 || $svc_acct->set_password($p->{'new_password'})
3022 || $svc_acct->replace();
3024 #regular pw change in self-service should change contact pw too, otherwise its
3025 #way too confusing. hell its confusing they're separate at all, but alas.
3026 #need to support the "ISP provides email that's used as a contact email" case
3028 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3029 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3030 custnum => $custnum,
3031 selfservice_access => 'Y',
3035 #svc_acct was successful but this one returns an error? "shouldn't happen"
3036 #don't recheck is_password_allowed here; if the svc_acct password was
3037 #legal, that's good enough
3038 $error ||= $contact->change_password($p->{'new_password'});
3041 my($label, $value) = $svc_acct->cust_svc->label;
3043 return { 'error' => $error,
3053 my $info = skin_info($p);
3055 my $conf = new FS::Conf;
3056 my $verification = $conf->config('selfservice-password_reset_verification')
3057 or return { %$info, 'error' => 'Password resets disabled' };
3062 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3064 $contact = FS::contact->by_selfservice_email($p->{'email'});
3067 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3068 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3071 #also look for an svc_acct, otherwise it would be super confusing
3073 my($username, $domain) = split('@', $p->{'email'});
3074 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3075 if ( $svc_domain ) {
3076 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3077 'domsvc' => $svc_domain->svcnum }
3080 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3081 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3083 #precaution: don't change svc_acct password not part of the same
3084 # customer as contact
3085 $svc_acct = '' if ! $cust_pkg
3086 || $cust_pkg->custnum != $cust_main->custnum;
3091 return { %$info, 'error' => 'Email address not found' }
3092 unless $contact || $svc_acct;
3094 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3096 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3097 or return { %$info, 'error' => 'Account not found' };
3099 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3100 'domsvc' => $svc_domain->svcnum }
3102 or return { %$info, 'error' => 'Account not found' };
3104 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3105 or return { %$info, 'error' => 'Account not found' };
3107 $cust_main = $cust_pkg->cust_main;
3111 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3112 if ! $cust_main && $verification ne 'email';
3115 'email' => sub { 1; },
3117 my( $p, $cust_main ) = @_;
3118 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3119 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3122 my( $p, $cust_main ) = @_;
3123 my $cust_pay = qsearchs({
3124 'table' => 'cust_pay',
3125 'hashref' => { 'custnum' => $cust_main->custnum },
3126 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3130 $p->{'amount'} == $cust_pay->paid;
3133 my( $p, $cust_main ) = @_;
3134 $p->{'zip'} eq $cust_main->zip
3135 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3139 foreach my $verify ( split(',', $verification) ) {
3141 &{ $verify{$verify} }( $p, $cust_main )
3142 or return { %$info, 'error' => 'Account not found' };
3146 #okay, we're verified
3150 my $error = $contact->send_reset_email(
3151 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3155 return { %$info, 'error' => $error }; #????
3158 } elsif ( $svc_acct ) {
3160 #create a unique session
3162 my $reset_session = {
3163 'svcnum' => $svc_acct->svcnum,
3164 'agentnum' => $svc_acct->cust_main->agentnum,
3167 my $timeout = '1 hour'; #?
3169 my $reset_session_id;
3171 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3172 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3175 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3179 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3180 $cust_main->agentnum);
3181 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3182 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3184 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3185 my $error = $msg_template->send( 'cust_main' => $cust_main,
3186 'object' => $svc_acct,
3187 'substitutions' => {
3188 'session_id' => $reset_session_id,
3192 return { %$info, 'error' => $error }; #????
3197 return { %$info, 'error' => '' };
3200 sub check_reset_passwd {
3203 my $conf = new FS::Conf;
3204 my $verification = $conf->config('selfservice-password_reset_verification')
3205 or return { 'error' => 'Password resets disabled' };
3207 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3208 or return { 'error' => "Can't resume session" }; #better error message
3210 if ( $reset_session->{'svcnum'} ) {
3212 my $svcnum = $reset_session->{'svcnum'};
3214 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3215 or return { 'error' => "Service not found" };
3217 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3218 my $info = skin_info($p);
3222 'session_id' => $p->{'session_id'},
3223 'username' => $svc_acct->username,
3226 } elsif ( $reset_session->{'contactnum'} ) {
3228 my $contactnum = $reset_session->{'contactnum'};
3230 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3231 or return { 'error' => "Contact not found" };
3233 my @contact_email = $contact->contact_email;
3234 return { 'error' => 'No contact email' } unless @contact_email;
3236 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3237 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3238 if scalar(@cust_contact) == 1;
3239 my $info = skin_info($p);
3243 'session_id' => $p->{'session_id'},
3244 'email' => $contact_email[0]->email, #the first?
3249 return { 'error' => 'No svcnum or contactnum in session' }; #??
3255 sub process_reset_passwd {
3258 my $conf = new FS::Conf;
3259 my $verification = $conf->config('selfservice-password_reset_verification')
3260 or return { 'error' => 'Password resets disabled' };
3262 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3263 or return { 'error' => "Can't resume session" }; #better error message
3268 if ( $reset_session->{'svcnum'} ) {
3270 my $svcnum = $reset_session->{'svcnum'};
3272 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3273 or return { 'error' => "Service not found" };
3275 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3276 $info ||= skin_info($p);
3281 if ( $reset_session->{'contactnum'} ) {
3283 my $contactnum = $reset_session->{'contactnum'};
3285 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3286 or return { 'error' => "Contact not found" };
3288 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3289 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3290 if scalar(@cust_contact) == 1;
3291 $info ||= skin_info($p);
3295 return { %$info, 'error' => "New passwords don't match." }
3296 if $p->{'new_password'} ne $p->{'new_password2'};
3298 return { %$info, 'error' => 'Enter new password' }
3299 unless length($p->{'new_password'});
3303 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3304 || $svc_acct->set_password($p->{'new_password'})
3305 || $svc_acct->replace();
3307 return { %$info, 'error' => $error } if $error;
3309 #my($label, $value) = $svc_acct->cust_svc->label;
3310 #return { 'error' => $error,
3311 # #'label' => $label,
3312 # #'value' => $value,
3319 my $error = $contact->is_password_allowed($p->{'new_password'})
3320 || $contact->change_password($p->{'new_password'});
3322 return { %$info, 'error' => $error }; # if $error;
3326 #password changed ,so remove session, don't want it reused
3327 _cache->remove($p->{'session_id'});
3329 return { %$info, 'error' => '' };
3333 sub validate_passwd {
3337 %result = ( 'fieldid' => $p->{'fieldid'} )
3338 if $p->{'fieldid'} =~ /^\w+$/;
3340 return { %result, 'password_invalid' => 'Enter new password' }
3341 unless length($p->{'check_password'});
3344 if ($p->{'svcnum'}) {
3345 # false laziness with myaccount_passwd
3346 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3347 return { %result, 'error' => $session } if $context eq 'error';
3349 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3350 my $search = " AND custnum = $1";
3351 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3353 $svc_acct = qsearchs( {
3354 'table' => 'svc_acct',
3355 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3356 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3357 'LEFT JOIN cust_main USING ( custnum ) ',
3358 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3359 'extra_sql' => $search, #important
3361 or return { %result, 'error' => "Service not found" };
3362 # end false laziness
3365 $svc_acct ||= new FS::svc_acct {};
3367 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3368 return { %result, 'password_invalid' => $error } if $error;
3369 return { %result, 'password_valid' => 1 };
3374 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3375 return { 'error' => $session } if $context eq 'error';
3378 if ( $session->{'pkgnum'} ) {
3380 #tickets for specific service with pkg-balances on
3381 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3382 'pkgnum' => $session->{'pkgnum'} })
3383 or return { 'error' => 'unknown package' };
3384 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3385 push @tickets, $cust_svc->tickets( $p->{status} );
3390 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3391 or return { 'error' => "unknown custnum $custnum" };
3393 @tickets = $cust_main->tickets( $p->{status} );
3396 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3397 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3398 my $conf = new FS::Conf;
3399 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3403 ($a->{'_selfservice_priority'} eq '') <=>
3404 ($b->{'_selfservice_priority'} eq '')
3407 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3413 +{ tickets => \@tickets };
3420 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3421 return { 'error' => $session } if $context eq 'error';
3423 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3424 FS::TicketSystem->init();
3426 my $conf = new FS::Conf;
3427 my $queue = $p->{'queue'}
3428 || $conf->config('ticket_system-selfservice_queueid')
3429 || $conf->config('ticket_system-default_queueid');
3431 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3432 my $err_or_ticket = FS::TicketSystem->create_ticket(
3433 '', #create RT session based on FS CurrentUser (fs_selfservice)
3435 'custnum' => $custnum,
3436 'svcnum' => $session->{'svcnum'},
3437 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3440 if ( ref($err_or_ticket) ) {
3441 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3443 return { 'error' => '',
3444 'ticket_id' => $err_or_ticket->id,
3447 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3449 return { 'error' => $err_or_ticket };
3457 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3458 return { 'error' => $session } if $context eq 'error';
3460 return { error => 'requested format not implemented' }
3461 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3463 my $conf = new FS::Conf;
3464 my $age_threshold = 0;
3465 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3466 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3468 my $search = { 'custnum' => $custnum };
3469 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3470 my $cust_main = qsearchs('cust_main', $search )
3471 or return { 'error' => "unknown custnum $custnum" };
3473 # does it make more sense to just run one sql query for this instead of all the
3474 # insanity below? would increase performance greately for large data sets?
3476 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3477 my @part_svc = $cust_pkg->part_svc;
3478 foreach my $part_svc ( @part_svc ) {
3479 if($part_svc->svcdb eq 'svc_phone'){
3480 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3481 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3482 push @svc_phone, $cust_pkg_svc->svc_x
3483 if $cust_pkg_svc->date_inserted >= $age_threshold;
3491 my($xls_r,$xls_c) = (0,0);
3494 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3495 if($p->{'format'} eq 'csv') {
3496 $csv = new Text::CSV_XS { 'always_quote' => 1,
3499 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3500 $content .= $csv->string;
3502 elsif($p->{'format'} eq 'xls') {
3503 my $XLS1 = new IO::Scalar \$content;
3504 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3505 or return { 'error' => "Error opening .xls file: $!" };
3506 $xls = $xls_workbook->add_worksheet('DIDs');
3507 foreach ( @fields ) {
3508 $xls->write(0,$xls_c++,$_);
3513 foreach my $svc_phone ( @svc_phone ) {
3514 my @cols = map { $svc_phone->$_ } @fields;
3515 if($p->{'format'} eq 'csv') {
3516 return { 'error' => 'Unable to create CSV' }
3517 unless $csv->combine(@cols);
3518 $content .= $csv->string;
3520 elsif($p->{'format'} eq 'xls') {
3523 $xls->write($xls_r,$xls_c++,$_);
3529 $xls_workbook->close() if $p->{'format'} eq 'xls';
3531 { content => $content, format => $p->{'format'}, };
3536 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3537 return { 'error' => $session } if $context eq 'error';
3539 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3540 # FS::TicketSystem->init();
3541 # return { 'error' => 'get_ticket configuration error' }
3542 # if $FS::TicketSystem::system ne 'RT_Internal';
3544 # check existence and ownership as part of this
3545 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3546 my $rt_session = FS::TicketSystem->session('');
3547 my $Ticket = FS::TicketSystem->get_ticket_object(
3549 ticket_id => $p->{'ticket_id'},
3552 return { 'error' => 'ticket not found' } if !$Ticket;
3554 if ( length( $p->{'subject'} || '' ) ) {
3556 if ( $p->{'subject'} ne $Ticket->Subject ) {
3557 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3558 return { 'error' => "unable to set subject: $msg" } if !$val;
3562 if(length($p->{'reply'})) {
3563 my @err_or_res = FS::TicketSystem->correspond_ticket(
3565 'ticket_id' => $p->{'ticket_id'},
3566 'content' => $p->{'reply'},
3569 return { 'error' => 'unable to reply to ticket' }
3570 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3573 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3574 my $err_or_ticket = FS::TicketSystem->get_ticket(
3576 'ticket_id' => $p->{'ticket_id'},
3579 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3580 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3582 return { 'error' => $err_or_ticket };
3585 my @custs = @{$err_or_ticket->{'custs'}};
3586 my @txns = @{$err_or_ticket->{'txns'}};
3589 # superseded by check in get_ticket_object
3590 #return { 'error' => 'invalid ticket requested' }
3591 #unless grep($_ eq $custnum, @custs);
3593 foreach my $txn ( @txns ) {
3594 push @filtered_txns, $txn
3595 if ($txn->{'type'} eq 'EmailRecord'
3596 || $txn->{'type'} eq 'Correspond'
3597 || $txn->{'type'} eq 'Create');
3600 warn "$me get_ticket: successful: \n"
3602 return { 'error' => '',
3603 'transactions' => \@filtered_txns,
3604 'ticket_fields' => $err_or_ticket->{'fields'},
3605 'ticket_id' => $p->{'ticket_id'},
3609 sub adjust_ticket_priority {
3611 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3612 return { 'error' => $session } if $context eq 'error';
3614 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3615 # FS::TicketSystem->init;
3616 my $ss_priority = FS::TicketSystem->selfservice_priority;
3618 return { 'error' => 'adjust_ticket_priority configuration error' }
3619 if $FS::TicketSystem::system ne 'RT_Internal'
3622 my $values = $p->{'values'}; #hashref, id => priority value
3625 foreach my $id (keys %$values) {
3626 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3627 my $Ticket = FS::TicketSystem->get_ticket_object('',
3629 'custnum' => $custnum,
3632 $ticket_error{$id} = 'ticket not found';
3636 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3637 # We're not going to implement it for RT_External.
3638 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3639 my $new_value = $values->{$id};
3640 next if $old_value eq $new_value;
3642 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3644 # AddCustomFieldValue works fine (replacing any existing value) if it's
3645 # a single-valued custom field, which it should be. If it's not, you're
3646 # doing something wrong.
3648 if ( length($new_value) ) {
3649 ($val, $msg) = $Ticket->AddCustomFieldValue(
3650 Field => $ss_priority,
3651 Value => $new_value,
3655 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3656 Field => $ss_priority,
3657 Value => $old_value,
3661 $ticket_error{$id} = $msg if !$val;
3662 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3664 return { 'error' => '',
3665 'ticket_error' => \%ticket_error,
3666 %{ customer_info($p) } # send updated customer info back
3672 sub _custoragent_session_custnum {
3675 my($context, $session, $custnum);
3676 if ( $p->{'session_id'} ) {
3678 $context = 'customer';
3679 $session = _cache->get($p->{'session_id'})
3680 or return ( 'error' => "Can't resume session" ); #better error message
3681 $custnum = $session->{'custnum'};
3683 } elsif ( $p->{'agent_session_id'} ) {
3686 my $agent_cache = new FS::ClientAPI_SessionCache( {
3687 'namespace' => 'FS::ClientAPI::Agent',
3689 $session = $agent_cache->get($p->{'agent_session_id'})
3690 or return ( 'error' => "Can't resume session" ); #better error message
3691 $custnum = $p->{'custnum'};
3695 return ( 'error' => "Can't resume session" ); #better error message
3698 ($context, $session, $custnum);