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;
52 # for code organization
53 use FS::ClientAPI::MyAccount::contact;
54 use FS::ClientAPI::MyAccount::quotation;
57 $me = '[FS::ClientAPI::MyAccount]';
59 use vars qw( @cust_main_editable_fields @location_editable_fields );
60 @cust_main_editable_fields = qw(
61 first last company daytime night fax mobile
63 payby payinfo payname paystart_month paystart_year payissue payip
64 ss paytype paystate 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 $return{payby} = $cust_main->payby;
631 #none of these are terribly expensive if we want 'em...
632 for (@cust_main_editable_fields) {
633 $return{$_} = $cust_main->get($_);
635 #maybe a little more expensive, but it should be cached by now
636 for (@location_editable_fields) {
637 $return{$_} = $cust_main->bill_location->get($_)
638 if $cust_main->bill_locationnum;
639 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
640 if $cust_main->ship_locationnum;
643 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
644 $return{payinfo} = $cust_main->paymask;
645 @return{'month', 'year'} = $cust_main->paydate_monthyear;
648 my @invoicing_list = $cust_main->invoicing_list;
649 $return{'invoicing_list'} =
650 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
651 $return{'postal_invoicing'} =
652 0 < ( grep { $_ eq 'POST' } @invoicing_list );
654 if ( $session->{'svcnum'} ) {
655 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
656 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
657 $return{'svcnum'} = $session->{'svcnum'};
660 } elsif ( $session->{'svcnum'} ) { #no customer record
662 #uuh, not supproted yet... die?
663 return { 'error' => 'customer_info_short not yet supported as agent' };
667 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
671 return { 'error' => '',
672 'custnum' => $custnum,
677 sub billing_history {
680 my($context, $session, $custnum) = _custoragent_session_custnum($p);
681 return { 'error' => $session } if $context eq 'error';
683 return { 'error' => 'No customer' } unless $custnum;
685 my $search = { 'custnum' => $custnum };
686 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
687 my $cust_main = qsearchs('cust_main', $search )
688 or return { 'error' => "unknown custnum $custnum" };
692 if ( $session->{'pkgnum'} ) {
693 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
694 #next_bill_date from cust_pkg?
695 return { 'error' => 'No history for package' };
698 $return{balance} = $cust_main->balance;
699 $return{balance_pretty} = money_pretty($return{balance});
700 $return{next_bill_date} = $cust_main->next_bill_date;
701 $return{next_bill_date_pretty} =
702 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
705 my $conf = new FS::Conf;
707 $return{'history'} = [
708 $cust_main->payment_history(
709 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
714 $return{'money_char'} = $conf->config("money_char") || '$',
722 my $session = _cache->get($p->{'session_id'})
723 or return { 'error' => "Can't resume session" }; #better error message
725 my $custnum = $session->{'custnum'}
726 or return { 'error' => "no customer record" };
728 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
729 or return { 'error' => "unknown custnum $custnum" };
731 my $new = new FS::cust_main { $cust_main->hash };
733 $new->set( $_ => $p->{$_} )
734 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
736 if ( exists($p->{address1}) ) {
737 my $bill_location = FS::cust_location->new({
738 map { $_ => $p->{$_} } @location_editable_fields
740 # if this is unchanged from before, cust_main::replace will ignore it
741 $new->set('bill_location' => $bill_location);
744 if ( exists($p->{ship_address1}) ) {
745 my $ship_location = FS::cust_location->new({
746 map { $_ => $p->{"ship_$_"} } @location_editable_fields
748 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
749 # Selfservice unfortunately tries to indicate "same as billing
750 # address" by sending all fields empty. Did this ever work?
751 $ship_location = $cust_main->bill_location;
753 $new->set('ship_location' => $ship_location);
755 # but if it hasn't been passed in at all, leave ship_location alone--
756 # DON'T change it to match bill_location.
759 if (exists($p->{'payby'})) {
760 $p->{'payby'} =~ /^([A-Z]{4})$/
761 or return { 'error' => "illegal_payby " . $p->{'payby'} };
765 my $conf = new FS::Conf;
767 if ( $payby =~ /^(CARD|DCRD)$/ ) {
769 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
771 if ( $new->payinfo eq $cust_main->paymask ) {
772 $new->payinfo($cust_main->payinfo);
773 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
775 $new->payinfo($p->{'payinfo'});
776 return { 'error' => 'CVV2 is required' }
777 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
778 $new->paycvv( $p->{'paycvv'} )
781 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
783 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
786 $p->{'payinfo1'} =~ /^([\dx]+)$/
787 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
789 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
790 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
792 $payinfo = $payinfo1. '@'. $payinfo2;
794 $new->payinfo( ($payinfo eq $cust_main->paymask)
795 ? $cust_main->payinfo
799 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
801 } elsif ( $payby =~ /^(BILL)$/ ) {
803 } elsif ( $payby ) { #notyet ready
804 return { 'error' => "unknown payby $payby" };
808 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
809 #false laziness with httemplate/edit/process/cust_main.cgi
810 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
811 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
813 @invoicing_list = $cust_main->invoicing_list;
816 my $error = $new->replace($cust_main, \@invoicing_list);
817 return { 'error' => $error } if $error;
820 return { 'error' => '' };
825 my $session = _cache->get($p->{'session_id'})
826 or return { 'error' => "Can't resume session" }; #better error message
832 my $conf = new FS::Conf;
833 use vars qw($payment_info); #cache for performance
834 unless ( $payment_info ) {
836 my %states = map { $_->state => 1 }
837 qsearch('cust_main_county', {
838 'country' => $conf->config('countrydefault') || 'US'
841 my %cust_paybys = map { $_ => 1 }
842 map { FS::payby->payby2payment($_) }
843 $conf->config('signup_server-payby');
845 my @cust_paybys = keys %cust_paybys;
849 #list all counties/states/countries
850 'cust_main_county' =>
851 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
853 #shortcut for one-country folks
855 [ sort { $a cmp $b } keys %states ],
857 'card_types' => card_types(),
859 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
860 'require_cvv' => $conf->exists('selfservice-require_cvv'),
861 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
863 'paytypes' => [ @FS::cust_main::paytypes ],
865 'paybys' => [ $conf->config('signup_server-payby') ],
866 'cust_paybys' => \@cust_paybys,
868 'stateid_label' => FS::Msgcat::_gettext('stateid'),
869 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
871 'show_ss' => $conf->exists('show_ss'),
872 'show_stateid' => $conf->exists('show_stateid'),
873 'show_paystate' => $conf->exists('show_bankstate'),
875 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
877 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
886 my %return = %$payment_info;
888 my $custnum = $session->{'custnum'};
890 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
891 or return { 'error' => "unknown custnum $custnum" };
893 $return{'hide_payment_fields'} = [
895 my $pg = payment_gateway($cust_main, $_);
896 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
897 } @{ $return{cust_paybys} }
900 $return{balance} = $cust_main->balance; #XXX pkg-balances?
902 $return{payname} = $cust_main->payname
903 || ( $cust_main->first. ' '. $cust_main->get('last') );
905 $return{$_} = $cust_main->bill_location->get($_)
906 for qw(address1 address2 city state zip);
908 $return{payby} = $cust_main->payby;
909 $return{stateid_state} = $cust_main->stateid_state;
911 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
912 $return{card_type} = cardtype($cust_main->payinfo);
913 $return{payinfo} = $cust_main->paymask;
915 @return{'month', 'year'} = $cust_main->paydate_monthyear;
919 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
920 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
921 $return{payinfo1} = $payinfo1;
922 $return{payinfo2} = $payinfo2;
923 $return{paytype} = $cust_main->paytype;
924 $return{paystate} = $cust_main->paystate;
925 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
928 if ( $conf->config('prepayment_discounts-credit_type') ) {
930 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
933 #doubleclick protection
935 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
936 $return{paybatch} = $return{payunique}; #back compat
938 return { 'error' => '',
944 #some false laziness with httemplate/process/payment.cgi - look there for
945 #ACH and CVV support stuff
947 sub validate_payment {
950 my $session = _cache->get($p->{'session_id'})
951 or return { 'error' => "Can't resume session" }; #better error message
953 my $custnum = $session->{'custnum'};
955 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
956 or return { 'error' => "unknown custnum $custnum" };
958 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
959 or return { 'error' => gettext('illegal_amount') };
961 return { error => 'Amount must be greater than 0' } unless $amount > 0;
963 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
964 #changing the hidden form values
965 my $conf = new FS::Conf;
966 my $fee_display = $conf->config('selfservice_process-display') || 'add';
967 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
968 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
969 if ( $fee_display eq 'add'
971 and ! $fee_skip_first || scalar($cust_main->cust_pay)
974 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
975 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
978 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
979 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
980 my $discount_term = $1;
982 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
983 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
986 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
987 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
990 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
991 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
994 $payunique = $paybatch if ! length($payunique) && length($paybatch);
996 $p->{'payby'} ||= 'CARD';
997 $p->{'payby'} =~ /^([A-Z]{4})$/
998 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1001 #false laziness w/process/payment.cgi
1004 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1006 $p->{'payinfo1'} =~ /^([\dx]+)$/
1007 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1009 $p->{'payinfo2'} =~ /^([\dx]+)$/
1010 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1012 $payinfo = $payinfo1. '@'. $payinfo2;
1014 $payinfo = $cust_main->payinfo
1015 if $cust_main->paymask eq $payinfo;
1017 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1019 $payinfo = $p->{'payinfo'};
1023 #more intelligent matching will be needed here if you change
1024 #card_masking_method and don't remove existing paymasks
1025 if ( $cust_main->paymask eq $payinfo ) {
1026 $payinfo = $cust_main->payinfo;
1030 $payinfo =~ s/\D//g;
1031 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1032 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1036 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1037 return { 'error' => gettext('unknown_card_type') }
1038 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1040 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1041 if ( cardtype($payinfo) eq 'American Express card' ) {
1042 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1043 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1046 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1047 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1050 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1051 return { 'error' => 'CVV2 is required' };
1052 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1053 return { 'error' => 'CVV2 is required' };
1057 die "unknown payby $payby";
1060 my %payby2fields = (
1061 'CARD' => [ qw( paystart_month paystart_year payissue payip
1062 address1 address2 city state zip country ) ],
1063 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1067 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1070 'cust_main' => $cust_main, #XXX or just custnum??
1071 'amount' => sprintf('%.2f', $amount),
1073 'payinfo' => $payinfo,
1074 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1075 'card_type' => $card_type,
1076 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1077 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1078 'month' => $p->{'month'},
1079 'year' => $p->{'year'},
1080 'payname' => $payname,
1081 'payunique' => $payunique,
1082 'paybatch' => $paybatch,
1083 'paycvv' => $paycvv,
1084 'payname' => $payname,
1085 'discount_term' => $discount_term,
1086 'pkgnum' => $session->{'pkgnum'},
1087 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1097 my $validate = validate_payment($p);
1098 return $validate if $validate->{'error'};
1100 my $conf = new FS::Conf;
1101 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1102 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1104 +{ map { $_=>$validate->{$_} }
1105 qw( card_type paymask payname paydate_pretty month year amount
1106 address1 address2 city state zip country
1112 sub process_stored_payment {
1115 my $session_id = $p->{'session_id'};
1117 my $payment_info = _cache->get( "payment_$session_id" )
1118 or return { 'error' => "Can't resume session" }; #better error message
1120 do_process_payment($payment_info);
1124 sub process_payment {
1127 my $payment_info = validate_payment($p);
1128 return $payment_info if $payment_info->{'error'};
1130 do_process_payment($payment_info);
1134 sub do_process_payment {
1135 my $validate = shift;
1137 my $cust_main = $validate->{'cust_main'};
1139 my $amount = delete $validate->{'amount'};
1142 my $payby = delete $validate->{'payby'};
1144 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1148 'paynum_ref' => \$paynum,
1151 return { 'error' => $error } if $error;
1153 #no error, so order the fee package if applicable...
1154 my $conf = new FS::Conf;
1155 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1156 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1158 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1160 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1162 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1163 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1166 #and generate an invoice for it now too
1167 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1168 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1173 $cust_main->apply_payments;
1175 if ( $validate->{'save'} ) {
1176 my $new = new FS::cust_main { $cust_main->hash };
1177 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1178 $new->set( $_ => $validate->{$_} )
1179 foreach qw( payname paystart_month paystart_year payissue payip );
1180 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1182 my $bill_location = FS::cust_location->new({
1183 map { $_ => $validate->{$_} }
1184 qw(address1 address2 city state country zip)
1186 $new->set('bill_location' => $bill_location);
1187 # but don't allow the service address to change this way.
1189 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1190 $new->set( $_ => $validate->{$_} )
1191 foreach qw( payname payip paytype paystate
1192 stateid stateid_state );
1193 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1195 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1196 $new->set( 'paydate' => $validate->{'paydate'} );
1197 my $error = $new->replace($cust_main);
1199 #no, this causes customers to process their payments again
1200 #return { 'error' => $error };
1201 #XXX just warn verosely for now so i can figure out how these happen in
1202 # the first place, eventually should redirect them to the "change
1203 #address" page but indicate the payment did process??
1204 delete($validate->{'payinfo'}); #don't want to log this!
1205 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1206 "NEW: ". Dumper($new)."\n".
1207 "OLD: ". Dumper($cust_main)."\n".
1208 "PACKET: ". Dumper($validate)."\n";
1216 my $receipt_html = '';
1218 # currently supported for realtime CC only; send receipt data to SS
1219 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1222 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1225 <TD ALIGN="right">Payment#</TD>
1226 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1230 <TD ALIGN="right">Date</TD>
1232 <TD BGCOLOR="#FFFFFF"><B>! .
1233 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1239 <TD ALIGN="right">Amount</TD>
1240 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1245 <TD ALIGN="right">Payment method</TD>
1246 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1259 'amount' => sprintf('%.2f', $cust_pay->paid),
1260 'date' => $cust_pay->_date,
1261 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1262 'time_pretty' => time2str('%T', $cust_pay->_date),
1263 'auth_num' => $cust_pay->auth,
1264 'order_num' => $cust_pay->order_number,
1265 'receipt_html' => $receipt_html,
1272 'receipt_html' => '',
1279 sub realtime_collect {
1282 my $session = _cache->get($p->{'session_id'})
1283 or return { 'error' => "Can't resume session" }; #better error message
1285 my $custnum = $session->{'custnum'};
1287 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1288 or return { 'error' => "unknown custnum $custnum" };
1291 if ( $p->{'amount'} ) {
1292 $amount = $p->{'amount'};
1294 elsif ( $session->{'pkgnum'} ) {
1295 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1298 $amount = $cust_main->balance;
1301 my $error = $cust_main->realtime_collect(
1302 'method' => $p->{'method'},
1303 'amount' => $amount,
1304 'pkgnum' => $session->{'pkgnum'},
1305 'session_id' => $p->{'session_id'},
1309 return { 'error' => $error } unless ref( $error );
1311 return { 'error' => '', amount => $amount, %$error };
1314 sub start_thirdparty {
1316 my $session = _cache->get($p->{'session_id'})
1317 or return { 'error' => "Can't resume session" }; #better error message
1318 my $custnum = $session->{'custnum'};
1319 my $cust_main = FS::cust_main->by_key($custnum);
1321 my $amount = $p->{'amount'}
1322 or return { error => 'no amount' };
1324 my $result = $cust_main->create_payment(
1325 'method' => $p->{'method'},
1326 'amount' => $p->{'amount'},
1327 'pkgnum' => $session->{'pkgnum'},
1328 'session_id' => $p->{'session_id'},
1331 if ( ref($result) ) { # hashref or error
1334 return { error => $result };
1338 sub finish_thirdparty {
1340 my $session_id = delete $p->{'session_id'};
1341 my $session = _cache->get($session_id)
1342 or return { 'error' => "Can't resume session" };
1343 my $custnum = $session->{'custnum'};
1344 my $cust_main = FS::cust_main->by_key($custnum);
1346 if ( $p->{_cancel} ) {
1347 # customer backed out of making a payment
1348 return $cust_main->cancel_payment( $session_id );
1350 my $result = $cust_main->execute_payment( $session_id, %$p );
1351 if ( ref($result) ) {
1354 return { error => $result };
1358 sub process_payment_order_pkg {
1361 my $hr = process_payment($p);
1362 return $hr if $hr->{'error'};
1367 sub process_payment_order_renew {
1370 my $hr = process_payment($p);
1371 return $hr if $hr->{'error'};
1376 sub process_prepay {
1380 my $session = _cache->get($p->{'session_id'})
1381 or return { 'error' => "Can't resume session" }; #better error message
1385 my $custnum = $session->{'custnum'};
1387 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1388 or return { 'error' => "unknown custnum $custnum" };
1390 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1391 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1399 return { 'error' => $error } if $error;
1401 return { 'error' => '',
1402 'amount' => $amount,
1403 'seconds' => $seconds,
1404 'duration' => duration_exact($seconds),
1405 'upbytes' => $upbytes,
1406 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1407 'downbytes' => $downbytes,
1408 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1409 'totalbytes'=> $totalbytes,
1410 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1417 my $session = _cache->get($p->{'session_id'})
1418 or return { 'error' => "Can't resume session" }; #better error message
1420 my $custnum = $session->{'custnum'};
1422 my $invnum = $p->{'invnum'};
1424 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1425 'custnum' => $custnum } )
1426 or return { 'error' => "Can't find invnum" };
1430 return { 'error' => '',
1431 'invnum' => $invnum,
1432 'invoice_text' => join('', $cust_bill->print_text ),
1433 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1440 my $session = _cache->get($p->{'session_id'})
1441 or return { 'error' => "Can't resume session" }; #better error message
1443 my $custnum = $session->{'custnum'};
1445 my $invnum = $p->{'invnum'};
1447 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1448 'custnum' => $custnum } )
1449 or return { 'error' => "Can't find invnum" };
1453 return { 'error' => '',
1454 'invnum' => $invnum,
1455 'invoice_pdf' => $cust_bill->print_pdf({
1456 'unsquelch_cdr' => 1,
1457 'locale' => $p->{'locale'},
1463 sub legacy_invoice {
1465 my $session = _cache->get($p->{'session_id'})
1466 or return { 'error' => "Can't resume session" }; #better error message
1468 my $custnum = $session->{'custnum'};
1470 my $legacyinvnum = $p->{'legacyinvnum'};
1473 'legacyinvnum' => $legacyinvnum,
1474 'custnum' => $custnum,
1477 my $legacy_cust_bill =
1478 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1479 || qsearchs('legacy_cust_bill', \%hash )
1480 or return { 'error' => "Can't find legacyinvnum" };
1484 return { 'error' => '',
1485 'legacyinvnum' => $legacyinvnum,
1486 'legacyid' => $legacy_cust_bill->legacyid,
1487 'invoice_html' => $legacy_cust_bill->content_html,
1492 sub legacy_invoice_pdf {
1494 my $session = _cache->get($p->{'session_id'})
1495 or return { 'error' => "Can't resume session" }; #better error message
1497 my $custnum = $session->{'custnum'};
1499 my $legacyinvnum = $p->{'legacyinvnum'};
1501 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1502 'legacyinvnum' => $legacyinvnum,
1503 'custnum' => $custnum,
1504 }) or return { 'error' => "Can't find legacyinvnum" };
1508 return { 'error' => '',
1509 'legacyinvnum' => $legacyinvnum,
1510 'legacyid' => $legacy_cust_bill->legacyid,
1511 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1519 #sessioning for this? how do we get the session id to the backend invoice
1520 # template so it can add it to the link, blah
1523 if ( $p->{'invnum'} ) {
1524 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1525 or return { 'error' => 'unknown invnum' };
1526 $agentnum = $cust_bill->cust_main->agentnum;
1529 my $templatename = $p->{'template'} || $p->{'templatename'};
1531 #false laziness-ish w/view/cust_bill-logo.cgi
1533 my $conf = new FS::Conf;
1534 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1535 $templatename = "_$1";
1540 my $filename = "logo$templatename.png";
1542 return { 'error' => '',
1543 'logo' => $conf->config_binary($filename, $agentnum),
1544 'content_type' => 'image/png', #should allow gif, jpg too
1551 my $session = _cache->get($p->{'session_id'})
1552 or return { 'error' => "Can't resume session" }; #better error message
1554 my $custnum = $session->{'custnum'};
1556 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1557 or return { 'error' => "unknown custnum $custnum" };
1559 my $conf = new FS::Conf;
1561 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1563 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1568 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1569 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1570 my $owed = $_->owed;
1572 +{ 'invnum' => $_->invnum,
1573 '_date' => $_->_date,
1574 'date' => time2str("%b %o, %Y", $_->_date),
1575 'date_short' => time2str("%m-%d-%Y", $_->_date),
1576 'previous' => sprintf('%.2f', ($_->previous)[0]),
1577 'charged' => sprintf('%.2f', $_->charged),
1578 'owed' => sprintf('%.2f', $owed),
1579 'balance' => sprintf('%.2f', $balance),
1580 'lastpay' => @payments_and_credits
1581 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1587 return { 'error' => '',
1588 'balance' => $cust_main->balance,
1589 'money_char' => $conf->config("money_char") || '$',
1590 'invoices' => $invoices,
1591 'legacy_invoices' => [
1593 +{ 'legacyinvnum' => $_->legacyinvnum,
1594 'legacyid' => $_->legacyid,
1595 '_date' => $_->_date,
1596 'date' => time2str("%b %o, %Y", $_->_date),
1597 'date_short' => time2str("%m-%d-%Y", $_->_date),
1598 'charged' => sprintf('%.2f', $_->charged),
1599 'has_content' => ( length($_->content_pdf)
1600 || length($_->content_html) ),
1610 my $session = _cache->get($p->{'session_id'})
1611 or return { 'error' => "Can't resume session" }; #better error message
1613 my $custnum = $session->{'custnum'};
1615 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1616 or return { 'error' => "unknown custnum $custnum" };
1618 my @errors = $cust_main->cancel( 'quiet'=>1 );
1620 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1622 return { 'error' => $error };
1629 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1630 return { 'error' => $session } if $context eq 'error';
1632 my $search = { 'custnum' => $custnum };
1633 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1634 my $cust_main = qsearchs('cust_main', $search )
1635 or return { 'error' => "unknown custnum $custnum" };
1637 my $conf = new FS::Conf;
1638 my $immutable = $conf->exists('selfservice_immutable-package');
1640 # the duplication below is necessary:
1641 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1642 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1643 # non-backwards-compatible change breaking the software of anyone using the API
1644 # instead of the stock selfservice
1645 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1646 if( $conf->exists('selfservice_server-view-wholesale') ) {
1647 return { 'svcnum' => $session->{'svcnum'},
1648 'custnum' => $custnum,
1649 'cust_pkg' => [ map {
1651 immutable => $immutable,
1652 part_pkg => [ map $_->hashref, $_->part_pkg ],
1654 [ map $_->hashref, $_->available_part_svc ],
1656 [ map { my $ref = { $_->hash,
1657 label => [ $_->label ],
1659 $ref->{_password} = $_->svc_x->_password
1660 if $context eq 'agent'
1661 && $conf->exists('agent-showpasswords')
1662 && $_->part_svc->svcdb eq 'svc_acct';
1667 } $cust_main->cust_pkg
1670 small_custview( $cust_main, $conf->config('countrydefault') ),
1671 'wholesale_view' => 1,
1672 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1673 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1674 'lnp' => $conf->exists('svc_phone-lnp'),
1678 { 'svcnum' => $session->{'svcnum'},
1679 'custnum' => $custnum,
1680 'cust_pkg' => [ map {
1681 my $primary_cust_svc = $_->primary_cust_svc;
1684 immutable => $immutable,
1685 pkg_label => $_->pkg_locale,
1686 status => $_->status,
1687 statuscolor => $_->statuscolor,
1689 [ map { $_->hashref }
1690 grep { $_->selfservice_access ne 'hidden' }
1691 $_->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';
1701 $ref->{svchash} = { $_->svc_x->hash } if
1702 $_->part_svc->svcdb eq 'svc_phone';
1703 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1704 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1707 grep { $_->part_svc->selfservice_access ne 'hidden' }
1712 ? { $primary_cust_svc->hash,
1713 label => [ $primary_cust_svc->label ],
1714 finger => $primary_cust_svc->svc_x->finger, #uuh
1715 $primary_cust_svc->part_svc->hash,
1719 } $cust_main->ncancelled_pkgs
1722 small_custview( $cust_main, $conf->config('countrydefault') ),
1723 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1731 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1732 return { 'error' => $session } if $context eq 'error';
1734 my $conf = new FS::Conf;
1736 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1737 my $search = { 'custnum' => $custnum };
1738 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1739 my $cust_main = qsearchs('cust_main', $search )
1740 or return { 'error' => "unknown custnum $custnum" };
1742 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1743 if ( ! $pkgnum && $p->{'svcnum'} ) {
1744 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1745 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1749 my @cust_pkg_usage = ();
1750 foreach my $cust_pkg ( $p->{'ncancelled'}
1751 ? $cust_main->ncancelled_pkgs
1752 : $cust_main->unsuspended_pkgs ) {
1753 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1754 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1755 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1758 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1761 foreach (@cust_pkg_usage) {
1762 my $part = $_->part_pkg_usage;
1763 my $tag = $part->description . ($part->shared ? 1 : 0);
1764 my $row = $usage_pools{$tag}
1765 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1766 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1767 $row->[2] += $part->minutes; # minutes total
1769 } # otherwise just leave them empty
1771 if ( $p->{'svcdb'} ) {
1772 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1774 : ref($p->{'svcdb'}) eq 'ARRAY'
1775 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1776 : { $p->{'svcdb'} => 1 };
1777 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1780 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1783 my @svcs; # stuff to return to the client
1784 foreach my $cust_svc (@cust_svc) {
1785 my $svc_x = $cust_svc->svc_x;
1786 my($label, $value) = $cust_svc->label;
1787 my $part_svc = $cust_svc->part_svc;
1788 my $svcdb = $part_svc->svcdb;
1789 my $cust_pkg = $cust_svc->cust_pkg;
1790 my $part_pkg = $cust_pkg->part_pkg;
1793 'svcnum' => $cust_svc->svcnum,
1794 'display_svcnum' => $cust_svc->display_svcnum,
1798 'pkg_label' => $cust_pkg->pkg_locale,
1799 'pkg_status' => $cust_pkg->status,
1800 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1803 # would it make sense to put this in a svc_* method?
1805 if ( $svcdb eq 'svc_acct' ) {
1806 foreach (qw(username email finger seconds)) {
1807 $hash{$_} = $svc_x->$_;
1813 'upbytes' => display_bytecount($svc_x->upbytes),
1814 'downbytes' => display_bytecount($svc_x->downbytes),
1815 'totalbytes' => display_bytecount($svc_x->totalbytes),
1817 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1818 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1819 'recharge_upbytes' =>
1820 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1821 'recharge_downbytes' =>
1822 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1823 'recharge_totalbytes' =>
1824 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1829 } elsif ( $svcdb eq 'svc_dsl' ) {
1831 $hash{'phonenum'} = $svc_x->phonenum;
1832 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1833 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1834 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1837 $hash{'name'} = $cust_main->name;
1839 # no usage to hide here
1841 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1843 # could potentially show lots of things...
1844 $hash{'outbound'} = 1;
1845 $hash{'inbound'} = 0;
1846 if ( $svcdb eq 'svc_phone' ) {
1847 if ( $part_pkg->plan eq 'voip_inbound' ) {
1848 $hash{'outbound'} = 0;
1849 $hash{'inbound'} = 1;
1850 } elsif ( $part_pkg->option('selfservice_inbound_format')
1851 or $conf->config('selfservice-default_inbound_cdr_format')
1853 $hash{'inbound'} = 1;
1856 foreach (qw(inbound outbound)) {
1857 # hmm...we can't filter by status here, because there might
1858 # not be cdr_terminations at all. have to go by date.
1859 # find all since the last bill date.
1860 # XXX cdr types? we are going to need them.
1862 my $sum_cdr = $svc_x->sum_cdrs(
1863 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1864 'begin' => ($cust_pkg->last_bill || 0),
1866 'disable_charged_party' => 1,
1868 $hash{$_} = $sum_cdr->hashref;
1871 } # not hiding usage
1875 } # foreach $cust_svc
1878 'svcnum' => $session->{'svcnum'},
1879 'custnum' => $custnum,
1880 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1881 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1884 map { $usage_pools{$_} }
1888 'hide_usage' => $hide_usage,
1893 sub _customer_svc_x {
1894 my($custnum, $svcnum, $table) = (shift, shift, shift);
1895 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1897 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1898 my $search = " AND custnum = $1";
1899 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1902 'table' => ($table || 'svc_acct'),
1903 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1904 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1905 #'LEFT JOIN cust_main USING ( custnum ) ',
1906 'hashref' => $hashref,
1907 'extra_sql' => $search, #important
1912 sub svc_status_html {
1915 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1916 return { 'error' => $session } if $context eq 'error';
1918 #XXX only svc_dsl for now
1919 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1920 or return { 'error' => "Service not found" };
1922 my $html = $svc_x->getstatus_html;
1924 return { 'html' => $html };
1928 sub svc_status_hash {
1931 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1932 return { 'error' => $session } if $context eq 'error';
1934 #XXX only svc_acct for now
1935 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1936 or return { 'error' => "Service not found" };
1938 my ( $html, $hashref ) = $svc_x->export_getstatus;
1943 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1944 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1945 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1946 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1947 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1950 my( $p, $method ) = @_;
1952 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1953 return { 'error' => $session } if $context eq 'error';
1955 #XXX only svc_acct for now
1956 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1957 or return { 'error' => "Service not found" };
1959 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1961 my $error = $svc_x->$method($p); #$p? returns error?
1962 return { 'error' => $error } if $error;
1964 return {}; #? { 'error' => '' }
1968 sub acct_forward_info {
1971 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1972 return { 'error' => $session } if $context eq 'error';
1974 my $svc_forward = _customer_svc_x( $custnum,
1975 { 'srcsvc' => $p->{'svcnum'} },
1978 or return { 'error' => '',
1982 return { 'error' => '',
1983 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1988 sub process_acct_forward {
1990 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1991 return { 'error' => $session } if $context eq 'error';
1993 my $old = _customer_svc_x( $custnum,
1994 { 'srcsvc' => $p->{'svcnum'} },
1998 if ( $p->{'dst'} eq '' ) {
2000 my $error = $old->delete;
2001 return { 'error' => $error };
2003 return { 'error' => '' };
2006 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2007 'dst' => $p->{'dst'},
2012 $new->svcnum($old->svcnum);
2013 my $cust_svc = $old->cust_svc;
2014 $new->svcpart($old->svcpart);
2015 $new->pkgnuym($old->pkgnum);
2016 $error = $new->replace($old);
2018 my $conf = new FS::Conf;
2019 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2021 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2022 or return { 'error' => 'No service' }; #how would we even get here?
2024 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2026 $error = $new->insert;
2029 return { 'error' => $error };
2033 sub list_dsl_devices {
2036 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2037 return { 'error' => $session } if $context eq 'error';
2039 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2040 or return { 'error' => "Service not found" };
2043 'devices' => [ map {
2044 +{ 'mac_addr' => $_->mac_addr };
2045 } $svc_dsl->dsl_device
2051 sub add_dsl_device {
2054 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2055 return { 'error' => $session } if $context eq 'error';
2057 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2058 or return { 'error' => "Service not found" };
2060 return { 'error' => 'No MAC address supplied' }
2061 unless length($p->{'mac_addr'});
2063 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2064 'mac_addr' => scalar($p->{'mac_addr'}),
2066 my $error = $dsl_device->insert;
2067 return { 'error' => $error };
2071 sub delete_dsl_device {
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" };
2080 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2081 'mac_addr' => scalar($p->{'mac_addr'}),
2084 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2086 my $error = $dsl_device->delete;
2087 return { 'error' => $error };
2093 _usage_details( \&_port_graph, $p,
2094 'svcdb' => 'svc_port',
2099 my($svc_port, $begin, $end) = @_;
2101 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2102 push @usage, { 'png' => $pngOrError };
2106 sub _list_svc_usage {
2107 my($svc_acct, $begin, $end) = @_;
2109 foreach my $part_export (
2110 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2111 qw( sqlradius sqlradius_withdomain )
2113 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2118 sub list_svc_usage {
2119 _usage_details(\&_list_svc_usage, @_);
2122 sub _list_support_usage {
2123 my($svc_acct, $begin, $end) = @_;
2125 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2126 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2128 push @usage, { 'seconds' => $_->seconds,
2129 'support' => $_->support,
2130 '_date' => $_->_date,
2131 'id' => $_->transaction_id,
2132 'creator' => $_->creator,
2133 'subject' => $_->subject,
2134 'status' => $_->status,
2135 'ticketid' => $_->ticketid,
2141 sub list_support_usage {
2142 _usage_details(\&_list_support_usage, @_);
2145 sub _list_cdr_usage {
2146 # XXX CDR type support...
2147 # XXX any way to do a paged search on this?
2148 # we have to return the results all at once...
2149 my($svc_x, $begin, $end, %opt) = @_;
2150 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2154 'disable_charged_party' => 1,
2159 sub list_cdr_usage {
2161 _usage_details( \&_list_cdr_usage, $p );
2164 sub _usage_details {
2165 my($callback, $p, %opt) = @_;
2166 my $conf = FS::Conf->new;
2168 if ( $conf->exists('selfservice_hide-usage') ) {
2169 return { 'error' => 'Viewing usage is not allowed.' };
2172 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2173 return { 'error' => $session } if $context eq 'error';
2175 my $search = { 'svcnum' => $p->{'svcnum'} };
2176 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2178 my $cust_svc = qsearchs( 'cust_svc', $search );
2179 return { 'error' => 'No service selected in list_svc_usage' }
2182 my $svc_x = $cust_svc->svc_x;
2183 my $svcdb = $svc_x->table;
2184 my $cust_pkg = $cust_svc->cust_pkg;
2185 my $freq = $cust_pkg->part_pkg->freq;
2188 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2190 if ( $p->{inbound} ) {
2191 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2192 || $conf->config('selfservice-default_inbound_cdr_format')
2193 || 'source_default';
2194 $callback_opt{inbound} = 1;
2196 $format = $cust_pkg->part_pkg->option('selfservice_format')
2197 || $conf->config('selfservice-default_cdr_format')
2201 $callback_opt{format} = $format;
2202 $callback_opt{use_clid} = 1;
2203 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2206 my $start = $cust_pkg->setup;
2207 #my $end = $cust_pkg->bill; # or time?
2210 unless ( $p->{beginning} ) {
2211 $p->{beginning} = $cust_pkg->last_bill;
2212 $p->{ending} = $end;
2215 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2216 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2218 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2222 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2223 # ugly kludge, I know
2224 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2225 if (defined $delete_col) {
2226 delete($_->[$delete_col]) foreach ($header, @usage);
2230 #kinda false laziness with FS::cust_main::bill, but perhaps
2231 #we should really change this bit to DateTime and DateTime::Duration
2233 #change this bit to use Date::Manip? CAREFUL with timezones (see
2234 # mailing list archive)
2235 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2236 (localtime($p->{ending}) )[0,1,2,3,4,5];
2237 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2238 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2240 if ( $freq =~ /^\d+$/ ) {
2242 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2244 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2245 } elsif ( $freq =~ /^(\d+)w$/ ) {
2247 $nmday += $weeks * 7;
2248 $pmday -= $weeks * 7;
2249 } elsif ( $freq =~ /^(\d+)d$/ ) {
2253 } elsif ( $freq =~ /^(\d+)h$/ ) {
2258 return { 'error' => "unparsable frequency: ". $freq };
2261 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2262 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2266 'svcnum' => $p->{svcnum},
2267 'beginning' => $p->{beginning},
2268 'ending' => $p->{ending},
2269 'inbound' => $p->{inbound},
2270 'previous' => ($previous > $start) ? $previous : $start,
2271 'next' => ($next < $end) ? $next : $end,
2272 'header' => $header,
2280 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2281 return { 'error' => $session } if $context eq 'error';
2283 my $search = { 'custnum' => $custnum };
2284 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2285 my $cust_main = qsearchs('cust_main', $search )
2286 or return { 'error' => "unknown custnum $custnum" };
2288 my $status = $cust_main->status;
2290 my %order_pkg_options = ();
2291 if ( $p->{locationnum} > 0 ) {
2292 $order_pkg_options{locationnum} = delete($p->{locationnum});
2293 } elsif ( $p->{address1} ) {
2294 $order_pkg_options{'cust_location'} = new FS::cust_location {
2295 map { $_ => $p->{$_} }
2296 qw( address1 address2 city county state zip country )
2300 #false laziness w/ClientAPI/Signup.pm
2302 my $cust_pkg = new FS::cust_pkg ( {
2303 'custnum' => $custnum,
2304 'pkgpart' => $p->{'pkgpart'},
2305 'quantity' => $p->{'quantity'} || 1,
2307 my $error = $cust_pkg->check;
2308 return { 'error' => $error } if $error;
2311 unless ( $p->{'svcpart'} eq 'none' ) {
2315 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2317 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2318 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2319 $svcdb = $part_svc->svcdb;
2321 $svcdb = 'svc_acct';
2323 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2326 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2327 'svc_domain' => [ qw( domain ) ],
2328 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2329 'svc_external' => [ qw( id title ) ],
2330 'svc_pbx' => [ qw( id title ) ],
2333 my $svc_x = "FS::$svcdb"->new( {
2334 'svcpart' => $svcpart,
2335 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2338 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2341 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2342 my $acct_snarf = new FS::acct_snarf ( {
2343 'machine' => $p->{"snarf_machine$snarfnum"},
2344 'protocol' => $p->{"snarf_protocol$snarfnum"},
2345 'username' => $p->{"snarf_username$snarfnum"},
2346 '_password' => $p->{"snarf_password$snarfnum"},
2349 push @acct_snarf, $acct_snarf;
2351 $svc_x->child_objects( \@acct_snarf );
2354 my $y = $svc_x->setdefault; # arguably should be in new method
2355 return { 'error' => $y } if $y && !ref($y);
2357 $error = $svc_x->check;
2358 return { 'error' => $error } if $error;
2364 $error = $cust_main->order_pkg(
2365 'cust_pkg' => $cust_pkg,
2370 return { 'error' => $error } if $error;
2372 my $conf = new FS::Conf;
2373 if ( $conf->exists('signup_server-realtime') ) {
2375 my $bill_error = _do_bop_realtime( $cust_main, $status );
2378 $cust_pkg->cancel('quiet'=>1);
2381 $cust_pkg->reexport;
2385 $cust_pkg->reexport;
2388 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2390 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2397 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2398 return { 'error' => $session } if $context eq 'error';
2400 my $conf = new FS::Conf;
2401 my $immutable = $conf->exists('selfservice_immutable-package');
2402 return { 'error' => "Package modification disabled" } if $immutable;
2404 my $search = { 'custnum' => $custnum };
2405 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2406 my $cust_main = qsearchs('cust_main', $search )
2407 or return { 'error' => "unknown custnum $custnum" };
2409 my $status = $cust_main->status;
2410 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2411 or return { 'error' => "unknown package $p->{pkgnum}" };
2413 #if someone does need self-service package change of suspended packages,
2414 # figure out how to be more discriminating
2415 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2416 if $cust_pkg->status eq 'suspended';
2418 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2419 'quantity' => $p->{'quantity'} || 1,
2422 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2423 unless ref($err_or_cust_pkg);
2425 if ( $conf->exists('signup_server-realtime') ) {
2427 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2430 $err_or_cust_pkg->suspend;
2433 $err_or_cust_pkg->reexport;
2437 $err_or_cust_pkg->reexport;
2440 return { error => '', pkgnum => $cust_pkg->pkgnum };
2444 sub order_recharge {
2447 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2448 return { 'error' => $session } if $context eq 'error';
2450 my $search = { 'custnum' => $custnum };
2451 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2452 my $cust_main = qsearchs('cust_main', $search )
2453 or return { 'error' => "unknown custnum $custnum" };
2455 my $status = $cust_main->status;
2456 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2457 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2459 my $svc_x = $cust_svc->svc_x;
2460 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2463 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2464 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2465 recharge_totalbytes );
2466 my $amount = $part_pkg->option('recharge_amount', 1);
2468 my ($l, $v, $d) = $cust_svc->label; # blah
2469 my $pkg = "Recharge $v";
2471 my $bill_error = $cust_main->charge($amount, $pkg,
2472 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2473 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2474 $part_pkg->taxclass); #meh
2476 my $conf = new FS::Conf;
2477 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2479 $bill_error = _do_bop_realtime( $cust_main, $status );
2484 my $error = $svc_x->recharge (\%vhash);
2485 return { 'error' => $error } if $error;
2489 my $error = $bill_error;
2490 $error ||= $svc_x->recharge (\%vhash);
2491 return { 'error' => $error } if $error;
2494 return { error => '', svc => $cust_svc->part_svc->svc };
2498 sub _do_bop_realtime {
2499 my ($cust_main, $status, %opt) = @_;
2501 my $old_balance = $cust_main->balance;
2503 my $bill_error = $cust_main->bill
2504 || $cust_main->apply_payments_and_credits;
2506 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2507 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2509 if ( $cust_main->balance > $old_balance
2510 && $cust_main->balance > 0
2511 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2512 || $status eq 'suspended'
2516 unless ( $opt{'no_credit'} ) {
2517 #this makes sense. credit is "un-doing" the invoice
2518 my $conf = new FS::Conf;
2519 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2520 'self-service decline',
2521 reason_type=>$conf->config('signup_credit_type'),
2523 $cust_main->apply_credits( 'order' => 'newest' );
2526 return { 'error' => '_decline', 'bill_error' => $bill_error };
2535 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2536 return { 'error' => $session } if $context eq 'error';
2538 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2539 or return { 'error' => "unknown custnum $custnum" };
2541 my @cust_pkg = sort { $a->bill <=> $b->bill }
2542 grep { $_->part_pkg->freq ne '0' }
2543 $cust_main->ncancelled_pkgs;
2545 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2547 my $total = $cust_main->balance;
2550 my $bill = $_->bill;
2551 $total += $_->part_pkg->base_recur($_, \$bill);
2552 my $renew_date = $_->part_pkg->add_freq($_->bill);
2554 'pkgnum' => $_->pkgnum,
2555 'amount' => sprintf('%.2f', $total),
2556 'bill_date' => $_->bill,
2557 'bill_date_pretty' => time2str('%x', $_->bill),
2558 'renew_date' => $renew_date,
2559 'renew_date_pretty' => time2str('%x', $renew_date),
2560 'expire_date' => $_->expire,
2561 'expire_date_pretty' => time2str('%x', $_->expire),
2566 return { 'dates' => \@array };
2570 sub payment_info_renew_info {
2572 my $renew_info = renew_info($p);
2573 my $payment_info = payment_info($p);
2574 return { %$renew_info,
2582 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2583 return { 'error' => $session } if $context eq 'error';
2585 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2586 or return { 'error' => "unknown custnum $custnum" };
2588 my $date = $p->{'date'};
2592 #freeside-daily -n -d $date fs_daily $custnum
2593 $cust_main->bill_and_collect( 'time' => $date,
2594 'invoice_time' => $now,
2595 'actual_time' => $now,
2596 'check_freq' => '1d',
2599 return { 'error' => '' };
2605 my $session = _cache->get($p->{'session_id'})
2606 or return { 'error' => "Can't resume session" }; #better error message
2608 my $custnum = $session->{'custnum'};
2610 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2611 or return { 'error' => "unknown custnum $custnum" };
2613 my $conf = new FS::Conf;
2615 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2616 or return { 'error' => 'Permission denied' };
2618 my $pkgnum = $p->{'pkgnum'};
2620 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2621 'pkgnum' => $pkgnum, } )
2622 or return { 'error' => "unknown pkgnum $pkgnum" };
2624 my $error = $cust_pkg->suspend(reason => $reasonnum);
2625 return { 'error' => $error };
2631 my $session = _cache->get($p->{'session_id'})
2632 or return { 'error' => "Can't resume session" }; #better error message
2634 my $custnum = $session->{'custnum'};
2636 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2637 or return { 'error' => "unknown custnum $custnum" };
2639 my $pkgnum = $p->{'pkgnum'};
2641 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2642 'pkgnum' => $pkgnum, } )
2643 or return { 'error' => "unknown pkgnum $pkgnum" };
2645 my $error = $cust_pkg->cancel('quiet' => 1);
2646 return { 'error' => $error };
2650 sub provision_phone {
2653 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2655 #editing an existing phone number
2656 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2657 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2658 return { 'error' => $session } if $context eq 'error';
2660 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2661 return { 'error' => 'service not found' } unless $svc_phone;
2662 return { 'error' => 'invalid svcnum' }
2663 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2665 $svc_phone->email($p->{'email'})
2666 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2667 $svc_phone->forwarddst($p->{'forwarddst'})
2668 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2669 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2670 return { 'error' => $svc_phone->replace };
2674 unless ( $p->{'lnp'} ) {
2675 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2676 $p->{'lnp_status'} = "portingin";
2677 return _provision( 'FS::svc_phone',
2678 [qw(lnp_desired_due_date lnp_other_provider
2679 lnp_other_provider_account phonenum countrycode lnp_status)],
2680 [qw(phonenum countrycode)],
2686 # single DID order (the usual case)
2687 unless (scalar(@bulkdid)) {
2688 return _provision( 'FS::svc_phone',
2689 [qw(phonenum countrycode)],
2690 [qw(phonenum countrycode)],
2696 # bulk DID order case
2698 foreach my $did ( @bulkdid ) {
2699 $did =~ s/[^0-9]//g;
2700 $error = _provision( 'FS::svc_phone',
2701 [qw(phonenum countrycode)],
2702 [qw(phonenum countrycode)],
2704 'pkgnum' => $p->{'pkgnum'},
2705 'svcpart' => $p->{'svcpart'},
2707 'countrycode' => $p->{'countrycode'},
2708 'session_id' => $p->{'session_id'},
2711 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2713 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2718 warn "provision_pbx called\n"
2721 warn "provision_pbx calling _provision\n"
2723 _provision( 'FS::svc_pbx',
2724 [qw(id title max_extensions max_simultaneous ip_addr)],
2725 [qw(id title max_extensions max_simultaneous ip_addr)],
2731 sub provision_acct {
2733 warn "provision_acct called\n"
2736 return { 'error' => gettext('passwords_dont_match') }
2737 if $p->{'_password'} ne $p->{'_password2'};
2738 return { 'error' => gettext('empty_password') }
2739 unless length($p->{'_password'});
2741 if ($p->{'domsvc'}) {
2742 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2743 qw ( svcpart pkgnum ) );
2744 return { 'error' => gettext('invalid_domain') }
2745 unless ($domains{$p->{'domsvc'}});
2748 warn "provision_acct calling _provision\n"
2750 _provision( 'FS::svc_acct',
2751 [qw(username _password domsvc)],
2752 [qw(username _password domsvc)],
2758 sub provision_external {
2760 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2761 _provision( 'FS::svc_external',
2769 sub provision_forward {
2771 _provision( 'FS::svc_forward',
2772 ['srcsvc','src','dstsvc','dst'],
2779 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2780 warn "_provision called for $class\n"
2783 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2784 return { 'error' => $session } if $context eq 'error';
2786 my $search = { 'custnum' => $custnum };
2787 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2788 my $cust_main = qsearchs('cust_main', $search )
2789 or return { 'error' => "unknown custnum $custnum" };
2791 my $pkgnum = $p->{'pkgnum'};
2793 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2795 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2796 'pkgnum' => $pkgnum,
2798 or return { 'error' => "unknown pkgnum $pkgnum" };
2800 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2802 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2803 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2805 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2806 if $class ne 'FS::'. $part_svc->svcdb;
2808 warn "creating $class record\n"
2810 my $svc_x = $class->new( {
2811 'pkgnum' => $p->{'pkgnum'},
2812 'svcpart' => $p->{'svcpart'},
2813 map { $_ => $p->{$_} } @$fields
2816 my %insert_args = ();
2817 #i shouldn't be a special case here (pass an option or something)
2818 if ( $class eq 'FS::svc_phone'
2819 && grep length($p->{$_}), @location_editable_fields
2822 $insert_args{'cust_location'} = new FS::cust_location {
2823 map { $_ => $p->{$_} } @location_editable_fields
2827 warn "inserting $class record\n"
2829 my $error = $svc_x->insert(%insert_args);
2832 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2834 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2837 my $return = { 'svc' => $part_svc->svc,
2839 map { $_ => $svc_x->get($_) } @$return_fields
2841 warn "_provision returning ". Dumper($return). "\n"
2850 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2851 return { 'error' => $session } if $context eq 'error';
2853 my $search = { 'custnum' => $custnum };
2854 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2855 my $cust_main = qsearchs('cust_main', $search )
2856 or return { 'error' => "unknown custnum $custnum" };
2858 my $pkgnum = $p->{'pkgnum'};
2860 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2861 'pkgnum' => $pkgnum,
2863 or return { 'error' => "unknown pkgnum $pkgnum" };
2865 my $svcpart = $p->{'svcpart'};
2867 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2868 'svcpart' => $svcpart, } )
2869 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2870 my $part_svc = $pkg_svc->part_svc;
2872 my $conf = new FS::Conf;
2875 'svc' => $part_svc->svc,
2876 'svcdb' => $part_svc->svcdb,
2877 'pkgnum' => $pkgnum,
2878 'svcpart' => $svcpart,
2879 'custnum' => $custnum,
2881 'security_phrase' => 0, #XXX !
2882 'svc_acct_pop' => [], #XXX !
2884 'init_popstate' => '',
2889 small_custview( $cust_main, $conf->config('countrydefault') ),
2893 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2894 && $ret->{'svcdb'} eq 'svc_phone') {
2895 $ret->{'svcnum'} = $p->{'svcnum'};
2896 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2897 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2898 $ret->{'email'} = $svc_phone->email;
2899 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2903 if ($ret->{'svcdb'} eq 'svc_forward') {
2904 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2910 sub unprovision_svc {
2913 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2914 return { 'error' => $session } if $context eq 'error';
2916 my $search = { 'custnum' => $custnum };
2917 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2918 my $cust_main = qsearchs('cust_main', $search )
2919 or return { 'error' => "unknown custnum $custnum" };
2921 my $svcnum = $p->{'svcnum'};
2923 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2924 or return { 'error' => "unknown svcnum $svcnum" };
2926 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2927 unless $cust_svc->cust_pkg->custnum == $custnum;
2929 my $conf = new FS::Conf;
2931 return { 'svc' => $cust_svc->part_svc->svc,
2932 'error' => $cust_svc->cancel,
2934 small_custview( $cust_main, $conf->config('countrydefault') ),
2939 sub myaccount_passwd {
2941 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2942 return { 'error' => $session } if $context eq 'error';
2944 return { 'error' => "New passwords don't match." }
2945 if $p->{'new_password'} ne $p->{'new_password2'};
2947 return { 'error' => 'Enter new password' }
2948 unless length($p->{'new_password'});
2950 #my $search = { 'custnum' => $custnum };
2951 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2952 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2953 my $search = " AND custnum = $1";
2954 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2956 my $svc_acct = qsearchs( {
2957 'table' => 'svc_acct',
2958 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2959 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2960 'LEFT JOIN cust_main USING ( custnum ) ',
2961 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2962 'extra_sql' => $search, #important
2964 or return { 'error' => "Service not found" };
2968 my $conf = new FS::Conf;
2970 return { 'error' => 'Incorrect current password.' }
2971 if ( exists($p->{'old_password'})
2972 || $conf->exists('selfservice-password_change_oldpass')
2974 && ! $svc_acct->check_password($p->{'old_password'});
2976 $error = 'Password too short.'
2977 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2978 $error = 'Password too long.'
2979 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2981 $svc_acct->set_password($p->{'new_password'});
2982 $error ||= $svc_acct->replace();
2984 #regular pw change in self-service should change contact pw too, otherwise its
2985 #way too confusing. hell its confusing they're separate at all, but alas.
2986 #need to support the "ISP provides email that's used as a contact email" case
2988 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2989 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
2990 custnum => $custnum,
2991 selfservice_access => 'Y',
2995 #svc_acct was successful but this one returns an error? "shouldn't happen"
2996 $error ||= $contact->change_password($p->{'new_password'});
2999 my($label, $value) = $svc_acct->cust_svc->label;
3001 return { 'error' => $error,
3011 my $info = skin_info($p);
3013 my $conf = new FS::Conf;
3014 my $verification = $conf->config('selfservice-password_reset_verification')
3015 or return { %$info, 'error' => 'Password resets disabled' };
3020 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3022 $contact = FS::contact->by_selfservice_email($p->{'email'});
3025 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3026 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3029 #also look for an svc_acct, otherwise it would be super confusing
3031 my($username, $domain) = split('@', $p->{'email'});
3032 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3033 if ( $svc_domain ) {
3034 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3035 'domsvc' => $svc_domain->svcnum }
3038 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3039 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3041 #precaution: don't change svc_acct password not part of the same
3042 # customer as contact
3043 $svc_acct = '' if ! $cust_pkg
3044 || $cust_pkg->custnum != $cust_main->custnum;
3049 return { %$info, 'error' => 'Email address not found' }
3050 unless $contact || $svc_acct;
3052 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3054 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3055 or return { %$info, 'error' => 'Account not found' };
3057 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3058 'domsvc' => $svc_domain->svcnum }
3060 or return { %$info, 'error' => 'Account not found' };
3062 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3063 or return { %$info, 'error' => 'Account not found' };
3065 $cust_main = $cust_pkg->cust_main;
3069 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3070 if ! $cust_main && $verification ne 'email';
3073 'email' => sub { 1; },
3075 my( $p, $cust_main ) = @_;
3076 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3077 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3080 my( $p, $cust_main ) = @_;
3081 my $cust_pay = qsearchs({
3082 'table' => 'cust_pay',
3083 'hashref' => { 'custnum' => $cust_main->custnum },
3084 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3088 $p->{'amount'} == $cust_pay->paid;
3091 my( $p, $cust_main ) = @_;
3092 $p->{'zip'} eq $cust_main->zip
3093 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3097 foreach my $verify ( split(',', $verification) ) {
3099 &{ $verify{$verify} }( $p, $cust_main )
3100 or return { %$info, 'error' => 'Account not found' };
3104 #okay, we're verified
3108 my $error = $contact->send_reset_email(
3109 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3113 return { %$info, 'error' => $error }; #????
3116 } elsif ( $svc_acct ) {
3118 #create a unique session
3120 my $reset_session = {
3121 'svcnum' => $svc_acct->svcnum,
3122 'agentnum' => $svc_acct->cust_main->agentnum,
3125 my $timeout = '1 hour'; #?
3127 my $reset_session_id;
3129 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3130 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3133 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3137 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3138 $cust_main->agentnum);
3139 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3140 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3142 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3143 my $error = $msg_template->send( 'cust_main' => $cust_main,
3144 'object' => $svc_acct,
3145 'substitutions' => {
3146 'session_id' => $reset_session_id,
3150 return { %$info, 'error' => $error }; #????
3155 return { %$info, 'error' => '' };
3158 sub check_reset_passwd {
3161 my $conf = new FS::Conf;
3162 my $verification = $conf->config('selfservice-password_reset_verification')
3163 or return { 'error' => 'Password resets disabled' };
3165 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3166 or return { 'error' => "Can't resume session" }; #better error message
3168 if ( $reset_session->{'svcnum'} ) {
3170 my $svcnum = $reset_session->{'svcnum'};
3172 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3173 or return { 'error' => "Service not found" };
3175 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3176 my $info = skin_info($p);
3180 'session_id' => $p->{'session_id'},
3181 'username' => $svc_acct->username,
3184 } elsif ( $reset_session->{'contactnum'} ) {
3186 my $contactnum = $reset_session->{'contactnum'};
3188 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3189 or return { 'error' => "Contact not found" };
3191 my @contact_email = $contact->contact_email;
3192 return { 'error' => 'No contact email' } unless @contact_email;
3194 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3195 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3196 if scalar(@cust_contact) == 1;
3197 my $info = skin_info($p);
3201 'session_id' => $p->{'session_id'},
3202 'email' => $contact_email[0]->email, #the first?
3207 return { 'error' => 'No svcnum or contactnum in session' }; #??
3213 sub process_reset_passwd {
3216 my $conf = new FS::Conf;
3217 my $verification = $conf->config('selfservice-password_reset_verification')
3218 or return { 'error' => 'Password resets disabled' };
3220 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3221 or return { 'error' => "Can't resume session" }; #better error message
3226 if ( $reset_session->{'svcnum'} ) {
3228 my $svcnum = $reset_session->{'svcnum'};
3230 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3231 or return { 'error' => "Service not found" };
3233 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3234 $info ||= skin_info($p);
3239 if ( $reset_session->{'contactnum'} ) {
3241 my $contactnum = $reset_session->{'contactnum'};
3243 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3244 or return { 'error' => "Contact not found" };
3246 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3247 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3248 if scalar(@cust_contact) == 1;
3249 $info ||= skin_info($p);
3253 return { %$info, 'error' => "New passwords don't match." }
3254 if $p->{'new_password'} ne $p->{'new_password2'};
3256 return { %$info, 'error' => 'Enter new password' }
3257 unless length($p->{'new_password'});
3261 $svc_acct->set_password($p->{'new_password'});
3262 my $error = $svc_acct->replace();
3264 return { %$info, 'error' => $error } if $error;
3266 #my($label, $value) = $svc_acct->cust_svc->label;
3267 #return { 'error' => $error,
3268 # #'label' => $label,
3269 # #'value' => $value,
3276 my $error = $contact->change_password($p->{'new_password'});
3278 return { %$info, 'error' => $error }; # if $error;
3282 #password changed ,so remove session, don't want it reused
3283 _cache->remove($p->{'session_id'});
3285 return { %$info, 'error' => '' };
3291 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3292 return { 'error' => $session } if $context eq 'error';
3295 if ( $session->{'pkgnum'} ) {
3297 #tickets for specific service with pkg-balances on
3298 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3299 'pkgnum' => $session->{'pkgnum'} })
3300 or return { 'error' => 'unknown package' };
3301 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3302 push @tickets, $cust_svc->tickets( $p->{status} );
3307 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3308 or return { 'error' => "unknown custnum $custnum" };
3310 @tickets = $cust_main->tickets( $p->{status} );
3313 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3314 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3315 my $conf = new FS::Conf;
3316 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3320 ($a->{'_selfservice_priority'} eq '') <=>
3321 ($b->{'_selfservice_priority'} eq '')
3324 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3330 +{ tickets => \@tickets };
3337 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3338 return { 'error' => $session } if $context eq 'error';
3340 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3341 FS::TicketSystem->init();
3343 my $conf = new FS::Conf;
3344 my $queue = $p->{'queue'}
3345 || $conf->config('ticket_system-selfservice_queueid')
3346 || $conf->config('ticket_system-default_queueid');
3348 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3349 my $err_or_ticket = FS::TicketSystem->create_ticket(
3350 '', #create RT session based on FS CurrentUser (fs_selfservice)
3352 'custnum' => $custnum,
3353 'svcnum' => $session->{'svcnum'},
3354 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3357 if ( ref($err_or_ticket) ) {
3358 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3360 return { 'error' => '',
3361 'ticket_id' => $err_or_ticket->id,
3364 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3366 return { 'error' => $err_or_ticket };
3374 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3375 return { 'error' => $session } if $context eq 'error';
3377 return { error => 'requested format not implemented' }
3378 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3380 my $conf = new FS::Conf;
3381 my $age_threshold = 0;
3382 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3383 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3385 my $search = { 'custnum' => $custnum };
3386 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3387 my $cust_main = qsearchs('cust_main', $search )
3388 or return { 'error' => "unknown custnum $custnum" };
3390 # does it make more sense to just run one sql query for this instead of all the
3391 # insanity below? would increase performance greately for large data sets?
3393 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3394 my @part_svc = $cust_pkg->part_svc;
3395 foreach my $part_svc ( @part_svc ) {
3396 if($part_svc->svcdb eq 'svc_phone'){
3397 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3398 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3399 push @svc_phone, $cust_pkg_svc->svc_x
3400 if $cust_pkg_svc->date_inserted >= $age_threshold;
3408 my($xls_r,$xls_c) = (0,0);
3411 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3412 if($p->{'format'} eq 'csv') {
3413 $csv = new Text::CSV_XS { 'always_quote' => 1,
3416 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3417 $content .= $csv->string;
3419 elsif($p->{'format'} eq 'xls') {
3420 my $XLS1 = new IO::Scalar \$content;
3421 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3422 or return { 'error' => "Error opening .xls file: $!" };
3423 $xls = $xls_workbook->add_worksheet('DIDs');
3424 foreach ( @fields ) {
3425 $xls->write(0,$xls_c++,$_);
3430 foreach my $svc_phone ( @svc_phone ) {
3431 my @cols = map { $svc_phone->$_ } @fields;
3432 if($p->{'format'} eq 'csv') {
3433 return { 'error' => 'Unable to create CSV' }
3434 unless $csv->combine(@cols);
3435 $content .= $csv->string;
3437 elsif($p->{'format'} eq 'xls') {
3440 $xls->write($xls_r,$xls_c++,$_);
3446 $xls_workbook->close() if $p->{'format'} eq 'xls';
3448 { content => $content, format => $p->{'format'}, };
3453 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3454 return { 'error' => $session } if $context eq 'error';
3456 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3457 # FS::TicketSystem->init();
3458 # return { 'error' => 'get_ticket configuration error' }
3459 # if $FS::TicketSystem::system ne 'RT_Internal';
3461 # check existence and ownership as part of this
3462 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3463 my $rt_session = FS::TicketSystem->session('');
3464 my $Ticket = FS::TicketSystem->get_ticket_object(
3466 ticket_id => $p->{'ticket_id'},
3469 return { 'error' => 'ticket not found' } if !$Ticket;
3471 if ( length( $p->{'subject'} || '' ) ) {
3473 if ( $p->{'subject'} ne $Ticket->Subject ) {
3474 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3475 return { 'error' => "unable to set subject: $msg" } if !$val;
3479 if(length($p->{'reply'})) {
3480 my @err_or_res = FS::TicketSystem->correspond_ticket(
3482 'ticket_id' => $p->{'ticket_id'},
3483 'content' => $p->{'reply'},
3486 return { 'error' => 'unable to reply to ticket' }
3487 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3490 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3491 my $err_or_ticket = FS::TicketSystem->get_ticket(
3493 'ticket_id' => $p->{'ticket_id'},
3496 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3497 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3499 return { 'error' => $err_or_ticket };
3502 my @custs = @{$err_or_ticket->{'custs'}};
3503 my @txns = @{$err_or_ticket->{'txns'}};
3506 # superseded by check in get_ticket_object
3507 #return { 'error' => 'invalid ticket requested' }
3508 #unless grep($_ eq $custnum, @custs);
3510 foreach my $txn ( @txns ) {
3511 push @filtered_txns, $txn
3512 if ($txn->{'type'} eq 'EmailRecord'
3513 || $txn->{'type'} eq 'Correspond'
3514 || $txn->{'type'} eq 'Create');
3517 warn "$me get_ticket: successful: \n"
3519 return { 'error' => '',
3520 'transactions' => \@filtered_txns,
3521 'ticket_fields' => $err_or_ticket->{'fields'},
3522 'ticket_id' => $p->{'ticket_id'},
3526 sub adjust_ticket_priority {
3528 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3529 return { 'error' => $session } if $context eq 'error';
3531 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3532 # FS::TicketSystem->init;
3533 my $ss_priority = FS::TicketSystem->selfservice_priority;
3535 return { 'error' => 'adjust_ticket_priority configuration error' }
3536 if $FS::TicketSystem::system ne 'RT_Internal'
3539 my $values = $p->{'values'}; #hashref, id => priority value
3542 foreach my $id (keys %$values) {
3543 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3544 my $Ticket = FS::TicketSystem->get_ticket_object('',
3546 'custnum' => $custnum,
3549 $ticket_error{$id} = 'ticket not found';
3553 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3554 # We're not going to implement it for RT_External.
3555 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3556 my $new_value = $values->{$id};
3557 next if $old_value eq $new_value;
3559 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3561 # AddCustomFieldValue works fine (replacing any existing value) if it's
3562 # a single-valued custom field, which it should be. If it's not, you're
3563 # doing something wrong.
3565 if ( length($new_value) ) {
3566 ($val, $msg) = $Ticket->AddCustomFieldValue(
3567 Field => $ss_priority,
3568 Value => $new_value,
3572 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3573 Field => $ss_priority,
3574 Value => $old_value,
3578 $ticket_error{$id} = $msg if !$val;
3579 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3581 return { 'error' => '',
3582 'ticket_error' => \%ticket_error,
3583 %{ customer_info($p) } # send updated customer info back
3589 sub _custoragent_session_custnum {
3592 my($context, $session, $custnum);
3593 if ( $p->{'session_id'} ) {
3595 $context = 'customer';
3596 $session = _cache->get($p->{'session_id'})
3597 or return ( 'error' => "Can't resume session" ); #better error message
3598 $custnum = $session->{'custnum'};
3600 } elsif ( $p->{'agent_session_id'} ) {
3603 my $agent_cache = new FS::ClientAPI_SessionCache( {
3604 'namespace' => 'FS::ClientAPI::Agent',
3606 $session = $agent_cache->get($p->{'agent_session_id'})
3607 or return ( 'error' => "Can't resume session" ); #better error message
3608 $custnum = $p->{'custnum'};
3612 return ( 'error' => "Can't resume session" ); #better error message
3615 ($context, $session, $custnum);