1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
58 $me = '[FS::ClientAPI::MyAccount]';
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62 first last company daytime night fax mobile
64 payby payinfo payname paystart_month paystart_year payissue payip
65 ss paytype paystate stateid stateid_state
67 @location_editable_fields = qw(
68 address1 address2 city county state zip country
72 BEGIN { #preload to reduce time customer_info takes
73 if ( $FS::TicketSystem::system ) {
74 warn "$me: initializing ticket system\n" if $DEBUG;
75 FS::TicketSystem->init();
80 $cache ||= new FS::ClientAPI_SessionCache( {
81 'namespace' => 'FS::ClientAPI::MyAccount',
88 my($context, $session, $custnum) = _custoragent_session_custnum($p);
89 #return { 'error' => $session } if $context eq 'error';
92 if ( $context eq 'customer' && $custnum ) {
94 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
97 $sth->execute($custnum) or die $sth->errstr;
99 $agentnum = $sth->fetchrow_arrayref->[0]
100 or die "no agentnum for custnum $custnum";
102 #} elsif ( $context eq 'agent' ) {
103 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
106 $p->{'agentnum'} = $agentnum;
108 my $conf = new FS::Conf;
110 #false laziness w/Signup.pm
112 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
114 if ( $skin_info_cache_agent ) {
116 warn "$me loading cached skin info for agentnum $agentnum\n"
121 warn "$me populating skin info cache for agentnum $agentnum\n"
124 $skin_info_cache_agent = {
125 'agentnum' => $agentnum,
126 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
127 qw( company_name date_format ) ),
128 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
129 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
130 text_color link_color vlink_color hlink_color alink_color
131 font title_color title_align title_size menu_bgcolor menu_fontsize
134 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
135 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
136 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
138 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
139 qw( title_left_image title_right_image
140 menu_top_image menu_body_image menu_bottom_image
143 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
144 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
145 qw( head body_header body_footer company_address ) ),
146 'money_char' => $conf->config("money_char") || '$',
147 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
150 services.php Services
151 services.php My Services
152 services_new.php Order a new service
155 personal.php Personal Information
156 password.php Change Password
159 payment_cc.php Credit Card Payment
160 payment_ach.php Electronic Check Payment
161 payment_paypal.php PayPal Payment
162 payment_webpay.php Webpay Payments
165 usage_data.php Data usage
166 usage_cdr.php Call usage
168 tickets.php Help Desk
169 tickets.php Open Tickets
170 tickets_resolved.php Resolved Tickets
171 ticket_create.php Create a new ticket
179 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
183 #{ %$skin_info_cache_agent };
184 $skin_info_cache_agent;
191 my $conf = new FS::Conf;
195 'phone_login' => $conf->exists('selfservice_server-phone_login'),
196 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
197 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
198 'banner_image_md5' =>
199 md5_hex($conf->config_binary('selfservice-login_banner_image')),
206 sub login_banner_image {
208 my $conf = new FS::Conf;
209 my $image = $conf->config_binary('selfservice-login_banner_image');
211 'md5' => md5_hex($image),
216 #false laziness w/FS::ClientAPI::passwd::passwd
220 my $conf = new FS::Conf;
224 if ( $p->{'domain'} eq 'svc_phone'
225 && $conf->exists('selfservice_server-phone_login') ) {
227 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
228 return { error => 'Number not found.' } unless $svc_phone;
231 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
232 #return { error => 'Only primary user may log in.' }
233 # if $conf->exists('selfservice_server-primary_only')
234 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
236 return { error => 'Incorrect PIN.' }
237 unless $svc_phone->check_pin($p->{'password'});
241 } elsif ( $p->{email}
242 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
245 return { error => 'Incorrect contact password.' }
246 unless $contact->authenticate_password($p->{'password'});
248 $session->{'contactnum'} = $contact->contactnum;
250 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
251 if ( scalar(@cust_contact) == 1 ) {
252 $session->{'custnum'} = $cust_contact[0]->custnum;
253 } elsif ( scalar(@cust_contact) ) {
254 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
258 return { error => 'No customer self-service access for contact' }; #??
263 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
265 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
266 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
268 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
269 'domsvc' => $svc_domain->svcnum, }
272 if ( $conf->exists('selfservice_server-login_svcpart') ) {
273 my @svcpart = $conf->config('selfservice_server-login_svcpart');
274 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
275 scalar( grep( $_ eq $svcpart, @svcpart ) );
280 if ( $conf->exists('selfservice_server-primary_only') ) {
283 my $cust_svc = $_->cust_svc;
284 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
285 == $cust_svc->svcpart
290 return { error => 'User not found.' } unless @svc_acct;
292 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
294 my $svc_acct = $svc_acct[0];
296 if ( $conf->exists('selfservice_server-login_svcpart') ) {
297 my @svcpart = $conf->config('selfservice_server-login_svcpart');
298 my $svcpart = $svc_acct->cust_svc->svcpart;
299 return { error => 'Invalid user.' }
300 unless grep($_ eq $svcpart, @svcpart);
303 return { error => 'Incorrect password.' }
304 unless $svc_acct->check_password($p->{'password'});
312 $session->{'svcnum'} = $svc_x->svcnum;
314 my $cust_svc = $svc_x->cust_svc;
315 my $cust_pkg = $cust_svc->cust_pkg;
317 my $cust_main = $cust_pkg->cust_main;
318 $session->{'custnum'} = $cust_main->custnum;
319 if ( $conf->exists('pkg-balances') ) {
320 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
321 $cust_main->ncancelled_pkgs;
322 $session->{'pkgnum'} = $cust_pkg->pkgnum
323 if scalar(@cust_pkg) > 1;
327 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
328 #return { error => 'Only primary user may log in.' }
329 # if $conf->exists('selfservice_server-primary_only')
330 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
331 my $part_pkg = $cust_pkg->part_pkg;
332 return { error => 'Only primary user may log in.' }
333 if $conf->exists('selfservice_server-primary_only')
334 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
340 $session_id = sha512_hex(time(). {}. rand(). $$)
341 } until ( ! defined _cache->get($session_id) ); #just in case
343 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
344 _cache->set( $session_id, $session, $timeout );
346 return { 'error' => '',
347 'session_id' => $session_id,
354 my $skin_info = skin_info($p);
355 if ( $p->{'session_id'} ) {
356 _cache->remove($p->{'session_id'});
357 return { %$skin_info, 'error' => '' };
359 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
366 my($context, $session, $custnum) = _custoragent_session_custnum($p);
367 return { 'error' => $session } if $context eq 'error';
369 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
370 or return { 'error' => "Service not found" };
372 $session->{'svcnum'} = $svc_acct->svcnum;
374 my $conf = new FS::Conf;
375 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
376 _cache->set( $p->{'session_id'}, $session, $timeout );
378 return { 'error' => '' };
384 my($context, $session, $custnum) = _custoragent_session_custnum($p);
385 return { 'error' => $session } if $context eq 'error';
387 $session->{'custnum'} = $p->{'custnum'}
388 if exists $session->{'customers'}{ $p->{'custnum'} };
390 my $conf = new FS::Conf;
391 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
392 _cache->set( $p->{'session_id'}, $session, $timeout );
394 return { 'error' => '',
395 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
399 sub payment_gateway {
401 # takes a cust_main and a cust_payby entry, returns the payment_gateway
402 my $conf = new FS::Conf;
403 my $cust_main = shift;
404 my $cust_payby = shift;
405 my $gatewaynum = $conf->config('selfservice-payment_gateway');
407 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
408 die "configured gatewaynum $gatewaynum not found!" if !$pg;
412 return '' if ! FS::payby->realtime($cust_payby);
413 my $pg = $cust_main->agent->payment_gateway(
414 'method' => FS::payby->payby2bop($cust_payby),
424 my $conf = new FS::Conf;
426 my $info = skin_info($p);
428 use vars qw( $cust_paybys ); #cache for performance
429 unless ( $cust_paybys ) {
431 my %cust_paybys = map { $_ => 1 }
432 map { FS::payby->payby2payment($_) }
433 $conf->config('signup_server-payby');
435 $cust_paybys = [ keys %cust_paybys ];
438 $info->{'cust_paybys'} = $cust_paybys;
440 my($context, $session, $custnum) = _custoragent_session_custnum($p);
441 return { 'error' => $session } if $context eq 'error';
443 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
445 $info->{'hide_payment_fields'} = [
447 my $pg = $cust_main && payment_gateway($cust_main, $_);
448 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
449 } @{ $info->{cust_paybys} }
452 $info->{'self_suspend_reason'} =
453 $conf->config('selfservice-self_suspend_reason',
454 $cust_main ? $cust_main->agentnum : ''
457 $info->{'edit_ticket_subject'} =
458 $conf->exists('ticket_system-selfservice_edit_subject') &&
459 $cust_main && $cust_main->edit_subject;
461 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
463 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
466 'custnum' => $custnum,
467 'access_pkgnum' => $session->{'pkgnum'},
468 'access_svcnum' => $session->{'svcnum'},
475 my($context, $session, $custnum) = _custoragent_session_custnum($p);
476 return { 'error' => $session } if $context eq 'error';
480 my $conf = new FS::Conf;
481 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
483 # if ( $FS::TicketSystem::system ) {
484 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
485 # FS::TicketSystem->init();
488 if ( $custnum ) { #customer record
490 %return = ( %return, %{ customer_info_short($p) } );
492 #redundant with customer_info_short, but we need it for several things below
493 my $search = { 'custnum' => $custnum };
494 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
495 my $cust_main = qsearchs('cust_main', $search )
496 or return { 'error' => "customer_info: unknown custnum $custnum" };
498 my $list_tickets = list_tickets($p);
499 $return{'tickets'} = $list_tickets->{'tickets'};
501 if ( $session->{'pkgnum'} ) {
502 #XXX open invoices in the pkg-balances case
504 $return{'money_char'} = $conf->config("money_char") || '$';
507 invnum => $_->invnum,
508 date => time2str("%b %o, %Y", $_->_date),
510 charged => $_->charged,
512 } $cust_main->open_cust_bill;
513 $return{open_invoices} = \@open;
515 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
516 my $sth = dbh->prepare($sql) or die dbh->errstr;
517 $sth->execute($custnum) or die $sth->errstr;
518 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
519 $return{'last_invoice_date_pretty'} =
520 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
523 #customer_info_short always has nobalance on..
524 $return{small_custview} =
525 small_custview( $cust_main,
526 $return{countrydefault},
527 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
530 $return{has_ship_address} = $cust_main->has_ship_address;
531 $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
532 $return{statuscolor} = $cust_main->statuscolor;
533 $return{status_label} = $cust_main->status_label;
535 # compatibility: some places in selfservice use this to determine
536 # if there's a ship address
537 if ( $return{has_ship_address} ) {
538 $return{ship_last} = $cust_main->last;
539 $return{ship_first} = $cust_main->first;
542 if (scalar($conf->config('support_packages'))) {
543 my @support_services = ();
544 foreach ($cust_main->support_services) {
545 my $seconds = $_->svc_x->seconds || 0;
546 my $time_remaining = (($seconds < 0) ? '-' : '' ).
547 int(abs($seconds)/3600)."h".
548 sprintf("%02d",(abs($seconds)%3600)/60)."m";
549 my $cust_pkg = $_->cust_pkg;
552 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
553 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
554 push @support_services, { svcnum => $_->svcnum,
555 time => $time_remaining,
560 $return{support_services} = \@support_services;
563 if ( $conf->config('prepayment_discounts-credit_type') ) {
565 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
568 } elsif ( $session->{'svcnum'} ) { #no customer record
570 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
571 or die "unknown svcnum";
572 $return{name} = $svc_acct->email;
576 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
580 return { 'error' => '',
581 'custnum' => $custnum,
587 sub customer_info_short {
590 my($context, $session, $custnum) = _custoragent_session_custnum($p);
591 return { 'error' => $session } if $context eq 'error';
595 my $conf = new FS::Conf;
597 if ( $custnum ) { #customer record
599 my $search = { 'custnum' => $custnum };
600 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
601 my $cust_main = qsearchs('cust_main', $search )
602 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
604 $return{display_custnum} = $cust_main->display_custnum;
606 if ( $session->{'pkgnum'} ) {
607 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
608 #next_bill_date from cust_pkg?
610 $return{balance} = $cust_main->balance;
611 $return{next_bill_date} = $cust_main->next_bill_date;
612 $return{next_bill_date_pretty} =
613 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
616 $return{balance_pretty} = money_pretty($return{balance});
618 $return{countrydefault} = scalar($conf->config('countrydefault'));
620 $return{small_custview} =
621 small_custview( $cust_main,
622 $return{countrydefault},
626 $return{first} = $cust_main->first;
627 $return{'last'} = $cust_main->get('last');
628 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
630 $return{payby} = $cust_main->payby;
632 #none of these are terribly expensive if we want 'em...
633 for (@cust_main_editable_fields) {
634 $return{$_} = $cust_main->get($_);
636 #maybe a little more expensive, but it should be cached by now
637 for (@location_editable_fields) {
638 $return{$_} = $cust_main->bill_location->get($_)
639 if $cust_main->bill_locationnum;
640 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
641 if $cust_main->ship_locationnum;
644 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
645 $return{payinfo} = $cust_main->paymask;
646 @return{'month', 'year'} = $cust_main->paydate_monthyear;
649 my @invoicing_list = $cust_main->invoicing_list;
650 $return{'invoicing_list'} =
651 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
652 $return{'postal_invoicing'} =
653 0 < ( grep { $_ eq 'POST' } @invoicing_list );
655 if ( $session->{'svcnum'} ) {
656 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
657 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
658 $return{'svcnum'} = $session->{'svcnum'};
661 } elsif ( $session->{'svcnum'} ) { #no customer record
663 #uuh, not supproted yet... die?
664 return { 'error' => 'customer_info_short not yet supported as agent' };
668 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
672 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
673 # it is not customer-specific, though it is only shown to authenticated customers
674 # it is not currently agent-specific, though at some point it might be
675 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
677 return { 'error' => '',
678 'custnum' => $custnum,
683 sub billing_history {
686 my($context, $session, $custnum) = _custoragent_session_custnum($p);
687 return { 'error' => $session } if $context eq 'error';
689 return { 'error' => 'No customer' } unless $custnum;
691 my $search = { 'custnum' => $custnum };
692 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
693 my $cust_main = qsearchs('cust_main', $search )
694 or return { 'error' => "unknown custnum $custnum" };
698 if ( $session->{'pkgnum'} ) {
699 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
700 #next_bill_date from cust_pkg?
701 return { 'error' => 'No history for package' };
704 $return{balance} = $cust_main->balance;
705 $return{balance_pretty} = money_pretty($return{balance});
706 $return{next_bill_date} = $cust_main->next_bill_date;
707 $return{next_bill_date_pretty} =
708 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
711 my $conf = new FS::Conf;
713 $return{'history'} = [
714 $cust_main->payment_history(
715 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
720 $return{'money_char'} = $conf->config("money_char") || '$',
728 my $session = _cache->get($p->{'session_id'})
729 or return { 'error' => "Can't resume session" }; #better error message
731 my $custnum = $session->{'custnum'}
732 or return { 'error' => "no customer record" };
734 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
735 or return { 'error' => "unknown custnum $custnum" };
737 my $new = new FS::cust_main { $cust_main->hash };
739 $new->set( $_ => $p->{$_} )
740 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
742 if ( exists($p->{address1}) ) {
743 my $bill_location = FS::cust_location->new({
744 map { $_ => $p->{$_} } @location_editable_fields
746 # if this is unchanged from before, cust_main::replace will ignore it
747 $new->set('bill_location' => $bill_location);
750 if ( exists($p->{ship_address1}) ) {
751 my $ship_location = FS::cust_location->new({
752 map { $_ => $p->{"ship_$_"} } @location_editable_fields
754 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
755 # Selfservice unfortunately tries to indicate "same as billing
756 # address" by sending all fields empty. Did this ever work?
757 $ship_location = $cust_main->bill_location;
759 $new->set('ship_location' => $ship_location);
761 # but if it hasn't been passed in at all, leave ship_location alone--
762 # DON'T change it to match bill_location.
765 if (exists($p->{'payby'})) {
766 $p->{'payby'} =~ /^([A-Z]{4})$/
767 or return { 'error' => "illegal_payby " . $p->{'payby'} };
771 my $conf = new FS::Conf;
773 if ( $payby =~ /^(CARD|DCRD)$/ ) {
775 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
777 if ( $new->payinfo eq $cust_main->paymask ) {
778 $new->payinfo($cust_main->payinfo);
779 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
781 $new->payinfo($p->{'payinfo'});
782 return { 'error' => 'CVV2 is required' }
783 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
784 $new->paycvv( $p->{'paycvv'} )
787 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
789 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
792 $p->{'payinfo1'} =~ /^([\dx]+)$/
793 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
795 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
796 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
798 $payinfo = $payinfo1. '@'. $payinfo2;
800 $new->payinfo( ($payinfo eq $cust_main->paymask)
801 ? $cust_main->payinfo
805 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
807 } elsif ( $payby =~ /^(BILL)$/ ) {
809 } elsif ( $payby ) { #notyet ready
810 return { 'error' => "unknown payby $payby" };
814 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
815 #false laziness with httemplate/edit/process/cust_main.cgi
816 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
817 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
819 @invoicing_list = $cust_main->invoicing_list;
822 my $error = $new->replace($cust_main, \@invoicing_list);
823 return { 'error' => $error } if $error;
826 return { 'error' => '' };
831 my $session = _cache->get($p->{'session_id'})
832 or return { 'error' => "Can't resume session" }; #better error message
838 my $conf = new FS::Conf;
839 use vars qw($payment_info); #cache for performance
840 unless ( $payment_info ) {
842 my %states = map { $_->state => 1 }
843 qsearch('cust_main_county', {
844 'country' => $conf->config('countrydefault') || 'US'
847 my %cust_paybys = map { $_ => 1 }
848 map { FS::payby->payby2payment($_) }
849 $conf->config('signup_server-payby');
851 my @cust_paybys = keys %cust_paybys;
855 #list all counties/states/countries
856 'cust_main_county' =>
857 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
859 #shortcut for one-country folks
861 [ sort { $a cmp $b } keys %states ],
863 'card_types' => card_types(),
865 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
866 'require_cvv' => $conf->exists('selfservice-require_cvv'),
867 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
869 'paytypes' => [ FS::cust_payby::paytypes ],
871 'paybys' => [ $conf->config('signup_server-payby') ],
872 'cust_paybys' => \@cust_paybys,
874 'stateid_label' => FS::Msgcat::_gettext('stateid'),
875 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
877 'show_ss' => $conf->exists('show_ss'),
878 'show_stateid' => $conf->exists('show_stateid'),
879 'show_paystate' => $conf->exists('show_bankstate'),
881 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
883 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
892 my %return = %$payment_info;
894 my $custnum = $session->{'custnum'};
896 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
897 or return { 'error' => "unknown custnum $custnum" };
899 $return{'hide_payment_fields'} = [
901 my $pg = payment_gateway($cust_main, $_);
902 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
903 } @{ $return{cust_paybys} }
906 $return{balance} = $cust_main->balance; #XXX pkg-balances?
908 $return{payname} = $cust_main->payname
909 || ( $cust_main->first. ' '. $cust_main->get('last') );
911 $return{$_} = $cust_main->bill_location->get($_)
912 for qw(address1 address2 city state zip);
914 $return{payby} = $cust_main->payby;
915 $return{stateid_state} = $cust_main->stateid_state;
917 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
918 $return{card_type} = cardtype($cust_main->payinfo);
919 $return{payinfo} = $cust_main->paymask;
921 @return{'month', 'year'} = $cust_main->paydate_monthyear;
925 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
926 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
927 $return{payinfo1} = $payinfo1;
928 $return{payinfo2} = $payinfo2;
929 $return{paytype} = $cust_main->paytype;
930 $return{paystate} = $cust_main->paystate;
931 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
934 if ( $conf->config('prepayment_discounts-credit_type') ) {
936 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
939 #doubleclick protection
941 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
942 $return{paybatch} = $return{payunique}; #back compat
944 return { 'error' => '',
950 #some false laziness with httemplate/process/payment.cgi - look there for
951 #ACH and CVV support stuff
953 sub validate_payment {
956 my $session = _cache->get($p->{'session_id'})
957 or return { 'error' => "Can't resume session" }; #better error message
959 my $custnum = $session->{'custnum'};
961 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
962 or return { 'error' => "unknown custnum $custnum" };
964 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
965 or return { 'error' => gettext('illegal_amount') };
967 return { error => 'Amount must be greater than 0' } unless $amount > 0;
969 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
970 #changing the hidden form values
971 my $conf = new FS::Conf;
972 my $fee_display = $conf->config('selfservice_process-display') || 'add';
973 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
974 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
975 if ( $fee_display eq 'add'
977 and ! $fee_skip_first || scalar($cust_main->cust_pay)
980 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
981 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
984 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
985 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
986 my $discount_term = $1;
988 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
989 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
992 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
993 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
996 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
997 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1000 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1002 $p->{'payby'} ||= 'CARD';
1003 $p->{'payby'} =~ /^([A-Z]{4})$/
1004 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1007 #false laziness w/process/payment.cgi
1010 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1012 $p->{'payinfo1'} =~ /^([\dx]+)$/
1013 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1015 $p->{'payinfo2'} =~ /^([\dx]+)$/
1016 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1018 $payinfo = $payinfo1. '@'. $payinfo2;
1020 $payinfo = $cust_main->payinfo
1021 if $cust_main->paymask eq $payinfo;
1023 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1025 $payinfo = $p->{'payinfo'};
1029 #more intelligent matching will be needed here if you change
1030 #card_masking_method and don't remove existing paymasks
1031 if ( $cust_main->paymask eq $payinfo ) {
1032 $payinfo = $cust_main->payinfo;
1036 $payinfo =~ s/\D//g;
1037 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1038 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1042 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1043 return { 'error' => gettext('unknown_card_type') }
1044 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1046 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1047 if ( cardtype($payinfo) eq 'American Express card' ) {
1048 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1049 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1052 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1053 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1056 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1057 return { 'error' => 'CVV2 is required' };
1058 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1059 return { 'error' => 'CVV2 is required' };
1063 die "unknown payby $payby";
1066 my %payby2fields = (
1067 'CARD' => [ qw( paystart_month paystart_year payissue payip
1068 address1 address2 city state zip country ) ],
1069 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1073 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1076 'cust_main' => $cust_main, #XXX or just custnum??
1077 'amount' => sprintf('%.2f', $amount),
1079 'payinfo' => $payinfo,
1080 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1081 'card_type' => $card_type,
1082 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1083 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1084 'month' => $p->{'month'},
1085 'year' => $p->{'year'},
1086 'payname' => $payname,
1087 'payunique' => $payunique,
1088 'paybatch' => $paybatch,
1089 'paycvv' => $paycvv,
1090 'payname' => $payname,
1091 'discount_term' => $discount_term,
1092 'pkgnum' => $session->{'pkgnum'},
1093 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1103 my $validate = validate_payment($p);
1104 return $validate if $validate->{'error'};
1106 my $conf = new FS::Conf;
1107 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1108 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1110 +{ map { $_=>$validate->{$_} }
1111 qw( card_type paymask payname paydate_pretty month year amount
1112 address1 address2 city state zip country
1118 sub process_stored_payment {
1121 my $session_id = $p->{'session_id'};
1123 my $payment_info = _cache->get( "payment_$session_id" )
1124 or return { 'error' => "Can't resume session" }; #better error message
1126 do_process_payment($payment_info);
1130 sub process_payment {
1133 my $payment_info = validate_payment($p);
1134 return $payment_info if $payment_info->{'error'};
1136 do_process_payment($payment_info);
1140 sub do_process_payment {
1141 my $validate = shift;
1143 my $cust_main = $validate->{'cust_main'};
1145 my $amount = delete $validate->{'amount'};
1148 my $payby = delete $validate->{'payby'};
1150 if ( $validate->{'save'} ) {
1151 my $new = new FS::cust_main { $cust_main->hash };
1152 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1153 $new->set( $_ => $validate->{$_} )
1154 foreach qw( payname paystart_month paystart_year payissue payip );
1155 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1157 my $bill_location = FS::cust_location->new({
1158 map { $_ => $validate->{$_} }
1159 qw(address1 address2 city state country zip)
1161 $new->set('bill_location' => $bill_location);
1162 # but don't allow the service address to change this way.
1164 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1165 $new->set( $_ => $validate->{$_} )
1166 foreach qw( payname payip paytype paystate
1167 stateid stateid_state );
1168 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1170 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1171 $new->set( 'paydate' => $validate->{'paydate'} );
1172 my $error = $new->replace($cust_main);
1174 #no, this causes customers to process their payments again
1175 #return { 'error' => $error };
1176 #XXX just warn verosely for now so i can figure out how these happen in
1177 # the first place, eventually should redirect them to the "change
1178 #address" page but indicate if the payment processed?
1179 delete($validate->{'payinfo'}); #don't want to log this!
1180 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1181 "NEW: ". Dumper($new)."\n".
1182 "OLD: ". Dumper($cust_main)."\n".
1183 "PACKET: ". Dumper($validate)."\n";
1189 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1193 'paynum_ref' => \$paynum,
1196 return { 'error' => $error } if $error;
1198 #no error, so order the fee package if applicable...
1199 my $conf = new FS::Conf;
1200 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1201 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1203 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1205 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1207 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1208 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1211 #and generate an invoice for it now too
1212 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1213 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1218 $cust_main->apply_payments;
1221 my $receipt_html = '';
1223 # currently supported for realtime CC only; send receipt data to SS
1224 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1227 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1230 <TD ALIGN="right">Payment#</TD>
1231 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1235 <TD ALIGN="right">Date</TD>
1237 <TD BGCOLOR="#FFFFFF"><B>! .
1238 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1244 <TD ALIGN="right">Amount</TD>
1245 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1250 <TD ALIGN="right">Payment method</TD>
1251 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1264 'amount' => sprintf('%.2f', $cust_pay->paid),
1265 'date' => $cust_pay->_date,
1266 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1267 'time_pretty' => time2str('%T', $cust_pay->_date),
1268 'auth_num' => $cust_pay->auth,
1269 'order_num' => $cust_pay->order_number,
1270 'receipt_html' => $receipt_html,
1277 'receipt_html' => '',
1284 sub realtime_collect {
1287 my $session = _cache->get($p->{'session_id'})
1288 or return { 'error' => "Can't resume session" }; #better error message
1290 my $custnum = $session->{'custnum'};
1292 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1293 or return { 'error' => "unknown custnum $custnum" };
1296 if ( $p->{'amount'} ) {
1297 $amount = $p->{'amount'};
1299 elsif ( $session->{'pkgnum'} ) {
1300 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1303 $amount = $cust_main->balance;
1306 my $error = $cust_main->realtime_collect(
1307 'method' => $p->{'method'},
1308 'amount' => $amount,
1309 'pkgnum' => $session->{'pkgnum'},
1310 'session_id' => $p->{'session_id'},
1314 return { 'error' => $error } unless ref( $error );
1316 return { 'error' => '', amount => $amount, %$error };
1319 sub start_thirdparty {
1321 my $session = _cache->get($p->{'session_id'})
1322 or return { 'error' => "Can't resume session" }; #better error message
1323 my $custnum = $session->{'custnum'};
1324 my $cust_main = FS::cust_main->by_key($custnum);
1326 my $amount = $p->{'amount'}
1327 or return { error => 'no amount' };
1329 my $result = $cust_main->create_payment(
1330 'method' => $p->{'method'},
1331 'amount' => $p->{'amount'},
1332 'pkgnum' => $session->{'pkgnum'},
1333 'session_id' => $p->{'session_id'},
1336 if ( ref($result) ) { # hashref or error
1339 return { error => $result };
1343 sub finish_thirdparty {
1345 my $session_id = delete $p->{'session_id'};
1346 my $session = _cache->get($session_id)
1347 or return { 'error' => "Can't resume session" };
1348 my $custnum = $session->{'custnum'};
1349 my $cust_main = FS::cust_main->by_key($custnum);
1351 if ( $p->{_cancel} ) {
1352 # customer backed out of making a payment
1353 return $cust_main->cancel_payment( $session_id );
1355 my $result = $cust_main->execute_payment( $session_id, %$p );
1356 if ( ref($result) ) {
1359 return { error => $result };
1363 sub process_payment_order_pkg {
1366 my $hr = process_payment($p);
1367 return $hr if $hr->{'error'};
1372 sub process_payment_order_renew {
1375 my $hr = process_payment($p);
1376 return $hr if $hr->{'error'};
1381 sub process_prepay {
1385 my $session = _cache->get($p->{'session_id'})
1386 or return { 'error' => "Can't resume session" }; #better error message
1390 my $custnum = $session->{'custnum'};
1392 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1393 or return { 'error' => "unknown custnum $custnum" };
1395 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1396 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1404 return { 'error' => $error } if $error;
1406 return { 'error' => '',
1407 'amount' => $amount,
1408 'seconds' => $seconds,
1409 'duration' => duration_exact($seconds),
1410 'upbytes' => $upbytes,
1411 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1412 'downbytes' => $downbytes,
1413 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1414 'totalbytes'=> $totalbytes,
1415 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1422 my $session = _cache->get($p->{'session_id'})
1423 or return { 'error' => "Can't resume session" }; #better error message
1425 my $custnum = $session->{'custnum'};
1427 my $invnum = $p->{'invnum'};
1429 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1430 'custnum' => $custnum } )
1431 or return { 'error' => "Can't find invnum" };
1435 return { 'error' => '',
1436 'invnum' => $invnum,
1437 'invoice_text' => join('', $cust_bill->print_text ),
1438 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1445 my $session = _cache->get($p->{'session_id'})
1446 or return { 'error' => "Can't resume session" }; #better error message
1448 my $custnum = $session->{'custnum'};
1450 my $invnum = $p->{'invnum'};
1452 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1453 'custnum' => $custnum } )
1454 or return { 'error' => "Can't find invnum" };
1458 return { 'error' => '',
1459 'invnum' => $invnum,
1460 'invoice_pdf' => $cust_bill->print_pdf({
1461 'unsquelch_cdr' => 1,
1462 'locale' => $p->{'locale'},
1468 sub legacy_invoice {
1470 my $session = _cache->get($p->{'session_id'})
1471 or return { 'error' => "Can't resume session" }; #better error message
1473 my $custnum = $session->{'custnum'};
1475 my $legacyinvnum = $p->{'legacyinvnum'};
1478 'legacyinvnum' => $legacyinvnum,
1479 'custnum' => $custnum,
1482 my $legacy_cust_bill =
1483 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1484 || qsearchs('legacy_cust_bill', \%hash )
1485 or return { 'error' => "Can't find legacyinvnum" };
1489 return { 'error' => '',
1490 'legacyinvnum' => $legacyinvnum,
1491 'legacyid' => $legacy_cust_bill->legacyid,
1492 'invoice_html' => $legacy_cust_bill->content_html,
1497 sub legacy_invoice_pdf {
1499 my $session = _cache->get($p->{'session_id'})
1500 or return { 'error' => "Can't resume session" }; #better error message
1502 my $custnum = $session->{'custnum'};
1504 my $legacyinvnum = $p->{'legacyinvnum'};
1506 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1507 'legacyinvnum' => $legacyinvnum,
1508 'custnum' => $custnum,
1509 }) or return { 'error' => "Can't find legacyinvnum" };
1513 return { 'error' => '',
1514 'legacyinvnum' => $legacyinvnum,
1515 'legacyid' => $legacy_cust_bill->legacyid,
1516 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1524 #sessioning for this? how do we get the session id to the backend invoice
1525 # template so it can add it to the link, blah
1528 if ( $p->{'invnum'} ) {
1529 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1530 or return { 'error' => 'unknown invnum' };
1531 $agentnum = $cust_bill->cust_main->agentnum;
1534 my $templatename = $p->{'template'} || $p->{'templatename'};
1536 #false laziness-ish w/view/cust_bill-logo.cgi
1538 my $conf = new FS::Conf;
1539 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1540 $templatename = "_$1";
1545 my $filename = "logo$templatename.png";
1547 return { 'error' => '',
1548 'logo' => $conf->config_binary($filename, $agentnum),
1549 'content_type' => 'image/png', #should allow gif, jpg too
1556 my $session = _cache->get($p->{'session_id'})
1557 or return { 'error' => "Can't resume session" }; #better error message
1559 my $custnum = $session->{'custnum'};
1561 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1562 or return { 'error' => "unknown custnum $custnum" };
1564 my $conf = new FS::Conf;
1566 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1568 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1573 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1574 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1575 my $owed = $_->owed;
1577 +{ 'invnum' => $_->invnum,
1578 '_date' => $_->_date,
1579 'date' => time2str("%b %o, %Y", $_->_date),
1580 'date_short' => time2str("%m-%d-%Y", $_->_date),
1581 'previous' => sprintf('%.2f', ($_->previous)[0]),
1582 'charged' => sprintf('%.2f', $_->charged),
1583 'owed' => sprintf('%.2f', $owed),
1584 'balance' => sprintf('%.2f', $balance),
1585 'lastpay' => @payments_and_credits
1586 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1592 return { 'error' => '',
1593 'balance' => $cust_main->balance,
1594 'money_char' => $conf->config("money_char") || '$',
1595 'invoices' => $invoices,
1596 'legacy_invoices' => [
1598 +{ 'legacyinvnum' => $_->legacyinvnum,
1599 'legacyid' => $_->legacyid,
1600 '_date' => $_->_date,
1601 'date' => time2str("%b %o, %Y", $_->_date),
1602 'date_short' => time2str("%m-%d-%Y", $_->_date),
1603 'charged' => sprintf('%.2f', $_->charged),
1604 'has_content' => ( length($_->content_pdf)
1605 || length($_->content_html) ),
1615 my $session = _cache->get($p->{'session_id'})
1616 or return { 'error' => "Can't resume session" }; #better error message
1618 my $custnum = $session->{'custnum'};
1620 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1621 or return { 'error' => "unknown custnum $custnum" };
1623 my @errors = $cust_main->cancel( 'quiet'=>1 );
1625 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1627 return { 'error' => $error };
1634 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1635 return { 'error' => $session } if $context eq 'error';
1637 my $search = { 'custnum' => $custnum };
1638 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1639 my $cust_main = qsearchs('cust_main', $search )
1640 or return { 'error' => "unknown custnum $custnum" };
1642 my $conf = new FS::Conf;
1643 my $immutable = $conf->exists('selfservice_immutable-package');
1645 # the duplication below is necessary:
1646 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1647 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1648 # non-backwards-compatible change breaking the software of anyone using the API
1649 # instead of the stock selfservice
1650 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1651 if( $conf->exists('selfservice_server-view-wholesale') ) {
1652 return { 'svcnum' => $session->{'svcnum'},
1653 'custnum' => $custnum,
1654 'cust_pkg' => [ map {
1656 immutable => $immutable,
1657 part_pkg => [ map $_->hashref, $_->part_pkg ],
1659 [ map $_->hashref, $_->available_part_svc ],
1661 [ map { my $ref = { $_->hash,
1662 label => [ $_->label ],
1664 $ref->{_password} = $_->svc_x->_password
1665 if $context eq 'agent'
1666 && $conf->exists('agent-showpasswords')
1667 && $_->part_svc->svcdb eq 'svc_acct';
1672 } $cust_main->cust_pkg
1675 small_custview( $cust_main, $conf->config('countrydefault') ),
1676 'wholesale_view' => 1,
1677 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1678 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1679 'lnp' => $conf->exists('svc_phone-lnp'),
1683 { 'svcnum' => $session->{'svcnum'},
1684 'custnum' => $custnum,
1685 'cust_pkg' => [ map {
1686 my $primary_cust_svc = $_->primary_cust_svc;
1689 immutable => $immutable,
1690 pkg_label => $_->pkg_locale,
1691 status => $_->status,
1692 statuscolor => $_->statuscolor,
1694 [ map { $_->hashref }
1695 grep { $_->selfservice_access ne 'hidden' }
1696 $_->available_part_svc
1699 [ map { my $ref = { $_->hash,
1700 label => [ $_->label ],
1702 $ref->{_password} = $_->svc_x->_password
1703 if $context eq 'agent'
1704 && $conf->exists('agent-showpasswords')
1705 && $_->part_svc->svcdb eq 'svc_acct';
1706 $ref->{svchash} = { $_->svc_x->hash } if
1707 $_->part_svc->svcdb eq 'svc_phone';
1708 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1709 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1712 grep { $_->part_svc->selfservice_access ne 'hidden' }
1717 ? { $primary_cust_svc->hash,
1718 label => [ $primary_cust_svc->label ],
1719 finger => $primary_cust_svc->svc_x->finger, #uuh
1720 $primary_cust_svc->part_svc->hash,
1724 } $cust_main->ncancelled_pkgs
1727 small_custview( $cust_main, $conf->config('countrydefault') ),
1728 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1736 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1737 return { 'error' => $session } if $context eq 'error';
1739 my $conf = new FS::Conf;
1741 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1742 my $search = { 'custnum' => $custnum };
1743 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1744 my $cust_main = qsearchs('cust_main', $search )
1745 or return { 'error' => "unknown custnum $custnum" };
1747 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1748 if ( ! $pkgnum && $p->{'svcnum'} ) {
1749 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1750 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1754 my @cust_pkg_usage = ();
1755 foreach my $cust_pkg ( $p->{'ncancelled'}
1756 ? $cust_main->ncancelled_pkgs
1757 : $cust_main->unsuspended_pkgs ) {
1758 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1759 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1760 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1763 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1766 foreach (@cust_pkg_usage) {
1767 my $part = $_->part_pkg_usage;
1768 my $tag = $part->description . ($part->shared ? 1 : 0);
1769 my $row = $usage_pools{$tag}
1770 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1771 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1772 $row->[2] += $part->minutes; # minutes total
1774 } # otherwise just leave them empty
1776 if ( $p->{'svcdb'} ) {
1777 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1779 : ref($p->{'svcdb'}) eq 'ARRAY'
1780 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1781 : { $p->{'svcdb'} => 1 };
1782 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1785 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1788 my @svcs; # stuff to return to the client
1789 foreach my $cust_svc (@cust_svc) {
1790 my $svc_x = $cust_svc->svc_x;
1791 my($label, $value) = $cust_svc->label;
1792 my $part_svc = $cust_svc->part_svc;
1793 my $svcdb = $part_svc->svcdb;
1794 my $cust_pkg = $cust_svc->cust_pkg;
1795 my $part_pkg = $cust_pkg->part_pkg;
1798 'svcnum' => $cust_svc->svcnum,
1799 'display_svcnum' => $cust_svc->display_svcnum,
1803 'pkg_label' => $cust_pkg->pkg_locale,
1804 'pkg_status' => $cust_pkg->status,
1805 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1808 # would it make sense to put this in a svc_* method?
1810 if ( $svcdb eq 'svc_acct' ) {
1811 foreach (qw(username email finger seconds)) {
1812 $hash{$_} = $svc_x->$_;
1818 'upbytes' => display_bytecount($svc_x->upbytes),
1819 'downbytes' => display_bytecount($svc_x->downbytes),
1820 'totalbytes' => display_bytecount($svc_x->totalbytes),
1822 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1823 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1824 'recharge_upbytes' =>
1825 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1826 'recharge_downbytes' =>
1827 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1828 'recharge_totalbytes' =>
1829 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1834 } elsif ( $svcdb eq 'svc_dsl' ) {
1836 $hash{'phonenum'} = $svc_x->phonenum;
1837 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1838 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1839 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1842 $hash{'name'} = $cust_main->name;
1844 # no usage to hide here
1846 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1848 # could potentially show lots of things...
1849 $hash{'outbound'} = 1;
1850 $hash{'inbound'} = 0;
1851 if ( $svcdb eq 'svc_phone' ) {
1852 if ( $part_pkg->plan eq 'voip_inbound' ) {
1853 $hash{'outbound'} = 0;
1854 $hash{'inbound'} = 1;
1855 } elsif ( $part_pkg->option('selfservice_inbound_format')
1856 or $conf->config('selfservice-default_inbound_cdr_format')
1858 $hash{'inbound'} = 1;
1861 foreach (qw(inbound outbound)) {
1862 # hmm...we can't filter by status here, because there might
1863 # not be cdr_terminations at all. have to go by date.
1864 # find all since the last bill date.
1865 # XXX cdr types? we are going to need them.
1867 my $sum_cdr = $svc_x->sum_cdrs(
1868 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1869 'begin' => ($cust_pkg->last_bill || 0),
1871 'disable_charged_party' => 1,
1873 $hash{$_} = $sum_cdr->hashref;
1876 } # not hiding usage
1880 } # foreach $cust_svc
1883 'svcnum' => $session->{'svcnum'},
1884 'custnum' => $custnum,
1885 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1886 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1889 map { $usage_pools{$_} }
1893 'hide_usage' => $hide_usage,
1898 sub _customer_svc_x {
1899 my($custnum, $svcnum, $table) = (shift, shift, shift);
1900 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1902 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1903 my $search = " AND custnum = $1";
1904 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1907 'table' => ($table || 'svc_acct'),
1908 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1909 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1910 #'LEFT JOIN cust_main USING ( custnum ) ',
1911 'hashref' => $hashref,
1912 'extra_sql' => $search, #important
1917 sub svc_status_html {
1920 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1921 return { 'error' => $session } if $context eq 'error';
1923 #XXX only svc_dsl for now
1924 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1925 or return { 'error' => "Service not found" };
1927 my $html = $svc_x->getstatus_html;
1929 return { 'html' => $html };
1933 sub svc_status_hash {
1936 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1937 return { 'error' => $session } if $context eq 'error';
1939 #XXX only svc_acct for now
1940 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1941 or return { 'error' => "Service not found" };
1943 my ( $html, $hashref ) = $svc_x->export_getstatus;
1948 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1949 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1950 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1951 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1952 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1955 my( $p, $method ) = @_;
1957 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1958 return { 'error' => $session } if $context eq 'error';
1960 #XXX only svc_acct for now
1961 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1962 or return { 'error' => "Service not found" };
1964 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1966 my $error = $svc_x->$method($p); #$p? returns error?
1967 return { 'error' => $error } if $error;
1969 return {}; #? { 'error' => '' }
1973 sub acct_forward_info {
1976 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1977 return { 'error' => $session } if $context eq 'error';
1979 my $svc_forward = _customer_svc_x( $custnum,
1980 { 'srcsvc' => $p->{'svcnum'} },
1983 or return { 'error' => '',
1987 return { 'error' => '',
1988 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1993 sub process_acct_forward {
1995 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1996 return { 'error' => $session } if $context eq 'error';
1998 my $old = _customer_svc_x( $custnum,
1999 { 'srcsvc' => $p->{'svcnum'} },
2003 if ( $p->{'dst'} eq '' ) {
2005 my $error = $old->delete;
2006 return { 'error' => $error };
2008 return { 'error' => '' };
2011 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2012 'dst' => $p->{'dst'},
2017 $new->svcnum($old->svcnum);
2018 my $cust_svc = $old->cust_svc;
2019 $new->svcpart($old->svcpart);
2020 $new->pkgnuym($old->pkgnum);
2021 $error = $new->replace($old);
2023 my $conf = new FS::Conf;
2024 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2026 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2027 or return { 'error' => 'No service' }; #how would we even get here?
2029 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2031 $error = $new->insert;
2034 return { 'error' => $error };
2038 sub list_dsl_devices {
2041 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2042 return { 'error' => $session } if $context eq 'error';
2044 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2045 or return { 'error' => "Service not found" };
2048 'devices' => [ map {
2049 +{ 'mac_addr' => $_->mac_addr };
2050 } $svc_dsl->dsl_device
2056 sub add_dsl_device {
2059 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2060 return { 'error' => $session } if $context eq 'error';
2062 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2063 or return { 'error' => "Service not found" };
2065 return { 'error' => 'No MAC address supplied' }
2066 unless length($p->{'mac_addr'});
2068 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2069 'mac_addr' => scalar($p->{'mac_addr'}),
2071 my $error = $dsl_device->insert;
2072 return { 'error' => $error };
2076 sub delete_dsl_device {
2079 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2080 return { 'error' => $session } if $context eq 'error';
2082 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2083 or return { 'error' => "Service not found" };
2085 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2086 'mac_addr' => scalar($p->{'mac_addr'}),
2089 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2091 my $error = $dsl_device->delete;
2092 return { 'error' => $error };
2098 _usage_details( \&_port_graph, $p,
2099 'svcdb' => 'svc_port',
2104 my($svc_port, $begin, $end) = @_;
2106 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2107 push @usage, { 'png' => $pngOrError };
2111 sub _list_svc_usage {
2112 my($svc_acct, $begin, $end) = @_;
2114 foreach my $part_export (
2115 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2116 qw( sqlradius sqlradius_withdomain )
2118 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2123 sub list_svc_usage {
2124 _usage_details(\&_list_svc_usage, @_);
2127 sub _list_support_usage {
2128 my($svc_acct, $begin, $end) = @_;
2130 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2131 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2133 push @usage, { 'seconds' => $_->seconds,
2134 'support' => $_->support,
2135 '_date' => $_->_date,
2136 'id' => $_->transaction_id,
2137 'creator' => $_->creator,
2138 'subject' => $_->subject,
2139 'status' => $_->status,
2140 'ticketid' => $_->ticketid,
2146 sub list_support_usage {
2147 _usage_details(\&_list_support_usage, @_);
2150 sub _list_cdr_usage {
2151 # XXX CDR type support...
2152 # XXX any way to do a paged search on this?
2153 # we have to return the results all at once...
2154 my($svc_x, $begin, $end, %opt) = @_;
2155 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2159 'disable_charged_party' => 1,
2164 sub list_cdr_usage {
2166 _usage_details( \&_list_cdr_usage, $p );
2169 sub _usage_details {
2170 my($callback, $p, %opt) = @_;
2171 my $conf = FS::Conf->new;
2173 if ( $conf->exists('selfservice_hide-usage') ) {
2174 return { 'error' => 'Viewing usage is not allowed.' };
2177 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2178 return { 'error' => $session } if $context eq 'error';
2180 my $search = { 'svcnum' => $p->{'svcnum'} };
2181 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2183 my $cust_svc = qsearchs( 'cust_svc', $search );
2184 return { 'error' => 'No service selected in list_svc_usage' }
2187 my $svc_x = $cust_svc->svc_x;
2188 my $svcdb = $svc_x->table;
2189 my $cust_pkg = $cust_svc->cust_pkg;
2190 my $freq = $cust_pkg->part_pkg->freq;
2193 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2195 if ( $p->{inbound} ) {
2196 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2197 || $conf->config('selfservice-default_inbound_cdr_format')
2198 || 'source_default';
2199 $callback_opt{inbound} = 1;
2201 $format = $cust_pkg->part_pkg->option('selfservice_format')
2202 || $conf->config('selfservice-default_cdr_format')
2206 $callback_opt{format} = $format;
2207 $callback_opt{use_clid} = 1;
2208 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2211 my $start = $cust_pkg->setup;
2212 #my $end = $cust_pkg->bill; # or time?
2215 unless ( $p->{beginning} ) {
2216 $p->{beginning} = $cust_pkg->last_bill;
2217 $p->{ending} = $end;
2220 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2221 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2223 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2227 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2228 # ugly kludge, I know
2229 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2230 if (defined $delete_col) {
2231 delete($_->[$delete_col]) foreach ($header, @usage);
2235 #kinda false laziness with FS::cust_main::bill, but perhaps
2236 #we should really change this bit to DateTime and DateTime::Duration
2238 #change this bit to use Date::Manip? CAREFUL with timezones (see
2239 # mailing list archive)
2240 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2241 (localtime($p->{ending}) )[0,1,2,3,4,5];
2242 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2243 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2245 if ( $freq =~ /^\d+$/ ) {
2247 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2249 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2250 } elsif ( $freq =~ /^(\d+)w$/ ) {
2252 $nmday += $weeks * 7;
2253 $pmday -= $weeks * 7;
2254 } elsif ( $freq =~ /^(\d+)d$/ ) {
2258 } elsif ( $freq =~ /^(\d+)h$/ ) {
2263 return { 'error' => "unparsable frequency: ". $freq };
2266 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2267 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2271 'svcnum' => $p->{svcnum},
2272 'beginning' => $p->{beginning},
2273 'ending' => $p->{ending},
2274 'inbound' => $p->{inbound},
2275 'previous' => ($previous > $start) ? $previous : $start,
2276 'next' => ($next < $end) ? $next : $end,
2277 'header' => $header,
2285 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2286 return { 'error' => $session } if $context eq 'error';
2288 my $search = { 'custnum' => $custnum };
2289 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2290 my $cust_main = qsearchs('cust_main', $search )
2291 or return { 'error' => "unknown custnum $custnum" };
2293 my $status = $cust_main->status;
2295 my %order_pkg_options = ();
2296 if ( $p->{locationnum} > 0 ) {
2297 $order_pkg_options{locationnum} = delete($p->{locationnum});
2298 } elsif ( $p->{address1} ) {
2299 $order_pkg_options{'cust_location'} = new FS::cust_location {
2300 map { $_ => $p->{$_} }
2301 qw( address1 address2 city county state zip country )
2305 #false laziness w/ClientAPI/Signup.pm
2307 my $cust_pkg = new FS::cust_pkg ( {
2308 'custnum' => $custnum,
2309 'pkgpart' => $p->{'pkgpart'},
2310 'quantity' => $p->{'quantity'} || 1,
2312 my $error = $cust_pkg->check;
2313 return { 'error' => $error } if $error;
2316 unless ( $p->{'svcpart'} eq 'none' ) {
2320 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2322 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2323 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2324 $svcdb = $part_svc->svcdb;
2326 $svcdb = 'svc_acct';
2328 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2331 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2332 'svc_domain' => [ qw( domain ) ],
2333 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2334 'svc_external' => [ qw( id title ) ],
2335 'svc_pbx' => [ qw( id title ) ],
2338 my $svc_x = "FS::$svcdb"->new( {
2339 'svcpart' => $svcpart,
2340 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2343 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2346 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2347 my $acct_snarf = new FS::acct_snarf ( {
2348 'machine' => $p->{"snarf_machine$snarfnum"},
2349 'protocol' => $p->{"snarf_protocol$snarfnum"},
2350 'username' => $p->{"snarf_username$snarfnum"},
2351 '_password' => $p->{"snarf_password$snarfnum"},
2354 push @acct_snarf, $acct_snarf;
2356 $svc_x->child_objects( \@acct_snarf );
2359 my $y = $svc_x->setdefault; # arguably should be in new method
2360 return { 'error' => $y } if $y && !ref($y);
2362 $error = $svc_x->check;
2363 return { 'error' => $error } if $error;
2369 $error = $cust_main->order_pkg(
2370 'cust_pkg' => $cust_pkg,
2375 return { 'error' => $error } if $error;
2377 my $conf = new FS::Conf;
2378 if ( $conf->exists('signup_server-realtime') ) {
2380 my $bill_error = _do_bop_realtime( $cust_main, $status );
2383 $cust_pkg->cancel('quiet'=>1);
2386 $cust_pkg->reexport;
2390 $cust_pkg->reexport;
2393 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2395 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2402 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2403 return { 'error' => $session } if $context eq 'error';
2405 my $conf = new FS::Conf;
2406 my $immutable = $conf->exists('selfservice_immutable-package');
2407 return { 'error' => "Package modification disabled" } if $immutable;
2409 my $search = { 'custnum' => $custnum };
2410 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2411 my $cust_main = qsearchs('cust_main', $search )
2412 or return { 'error' => "unknown custnum $custnum" };
2414 my $status = $cust_main->status;
2415 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2416 or return { 'error' => "unknown package $p->{pkgnum}" };
2418 #if someone does need self-service package change of suspended packages,
2419 # figure out how to be more discriminating
2420 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2421 if $cust_pkg->status eq 'suspended';
2423 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2424 'quantity' => $p->{'quantity'} || 1,
2427 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2428 unless ref($err_or_cust_pkg);
2430 if ( $conf->exists('signup_server-realtime') ) {
2432 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2435 $err_or_cust_pkg->suspend;
2438 $err_or_cust_pkg->reexport;
2442 $err_or_cust_pkg->reexport;
2445 return { error => '', pkgnum => $cust_pkg->pkgnum };
2449 sub order_recharge {
2452 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2453 return { 'error' => $session } if $context eq 'error';
2455 my $search = { 'custnum' => $custnum };
2456 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2457 my $cust_main = qsearchs('cust_main', $search )
2458 or return { 'error' => "unknown custnum $custnum" };
2460 my $status = $cust_main->status;
2461 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2462 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2464 my $svc_x = $cust_svc->svc_x;
2465 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2468 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2469 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2470 recharge_totalbytes );
2471 my $amount = $part_pkg->option('recharge_amount', 1);
2473 my ($l, $v, $d) = $cust_svc->label; # blah
2474 my $pkg = "Recharge $v";
2476 my $bill_error = $cust_main->charge($amount, $pkg,
2477 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2478 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2479 $part_pkg->taxclass); #meh
2481 my $conf = new FS::Conf;
2482 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2484 $bill_error = _do_bop_realtime( $cust_main, $status );
2489 my $error = $svc_x->recharge (\%vhash);
2490 return { 'error' => $error } if $error;
2494 my $error = $bill_error;
2495 $error ||= $svc_x->recharge (\%vhash);
2496 return { 'error' => $error } if $error;
2499 return { error => '', svc => $cust_svc->part_svc->svc };
2503 sub _do_bop_realtime {
2504 my ($cust_main, $status, %opt) = @_;
2506 my $old_balance = $cust_main->balance;
2509 my $bill_error = $cust_main->bill(
2510 'return_bill' => \@cust_bill,
2513 $bill_error ||= $cust_main->apply_payments_and_credits;
2515 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2516 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2518 if ( $cust_main->balance > $old_balance
2519 && $cust_main->balance > 0
2520 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2521 || $status eq 'suspended'
2525 unless ( $opt{'no_invoice_void'} ) {
2527 #this used to apply a credit, but now we can void invoices...
2528 foreach my $cust_bill (@cust_bill) {
2529 my $voiderror = $cust_bill->void('automatic payment failed');
2530 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2535 return { 'error' => '_decline', 'bill_error' => $bill_error };
2544 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2545 return { 'error' => $session } if $context eq 'error';
2547 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2548 or return { 'error' => "unknown custnum $custnum" };
2550 my @cust_pkg = sort { $a->bill <=> $b->bill }
2551 grep { $_->part_pkg->freq ne '0' }
2552 $cust_main->ncancelled_pkgs;
2554 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2556 my $total = $cust_main->balance;
2559 my $bill = $_->bill;
2560 $total += $_->part_pkg->base_recur($_, \$bill);
2561 my $renew_date = $_->part_pkg->add_freq($_->bill);
2563 'pkgnum' => $_->pkgnum,
2564 'amount' => sprintf('%.2f', $total),
2565 'bill_date' => $_->bill,
2566 'bill_date_pretty' => time2str('%x', $_->bill),
2567 'renew_date' => $renew_date,
2568 'renew_date_pretty' => time2str('%x', $renew_date),
2569 'expire_date' => $_->expire,
2570 'expire_date_pretty' => time2str('%x', $_->expire),
2575 return { 'dates' => \@array };
2579 sub payment_info_renew_info {
2581 my $renew_info = renew_info($p);
2582 my $payment_info = payment_info($p);
2583 return { %$renew_info,
2591 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2592 return { 'error' => $session } if $context eq 'error';
2594 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2595 or return { 'error' => "unknown custnum $custnum" };
2597 my $date = $p->{'date'};
2601 #freeside-daily -n -d $date fs_daily $custnum
2602 $cust_main->bill_and_collect( 'time' => $date,
2603 'invoice_time' => $now,
2604 'actual_time' => $now,
2605 'check_freq' => '1d',
2608 return { 'error' => '' };
2614 my $session = _cache->get($p->{'session_id'})
2615 or return { 'error' => "Can't resume session" }; #better error message
2617 my $custnum = $session->{'custnum'};
2619 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2620 or return { 'error' => "unknown custnum $custnum" };
2622 my $conf = new FS::Conf;
2624 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2625 or return { 'error' => 'Permission denied' };
2627 my $pkgnum = $p->{'pkgnum'};
2629 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2630 'pkgnum' => $pkgnum, } )
2631 or return { 'error' => "unknown pkgnum $pkgnum" };
2633 my $error = $cust_pkg->suspend(reason => $reasonnum);
2634 return { 'error' => $error };
2640 my $session = _cache->get($p->{'session_id'})
2641 or return { 'error' => "Can't resume session" }; #better error message
2643 my $custnum = $session->{'custnum'};
2645 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2646 or return { 'error' => "unknown custnum $custnum" };
2648 my $pkgnum = $p->{'pkgnum'};
2650 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2651 'pkgnum' => $pkgnum, } )
2652 or return { 'error' => "unknown pkgnum $pkgnum" };
2654 my $error = $cust_pkg->cancel('quiet' => 1);
2655 return { 'error' => $error };
2659 sub provision_phone {
2662 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2664 #editing an existing phone number
2665 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2666 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2667 return { 'error' => $session } if $context eq 'error';
2669 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2670 return { 'error' => 'service not found' } unless $svc_phone;
2671 return { 'error' => 'invalid svcnum' }
2672 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2674 $svc_phone->email($p->{'email'})
2675 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2676 $svc_phone->forwarddst($p->{'forwarddst'})
2677 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2678 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2679 return { 'error' => $svc_phone->replace };
2683 unless ( $p->{'lnp'} ) {
2684 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2685 $p->{'lnp_status'} = "portingin";
2686 return _provision( 'FS::svc_phone',
2687 [qw(lnp_desired_due_date lnp_other_provider
2688 lnp_other_provider_account phonenum countrycode lnp_status)],
2689 [qw(phonenum countrycode)],
2695 # single DID order (the usual case)
2696 unless (scalar(@bulkdid)) {
2697 return _provision( 'FS::svc_phone',
2698 [qw(phonenum countrycode)],
2699 [qw(phonenum countrycode)],
2705 # bulk DID order case
2707 foreach my $did ( @bulkdid ) {
2708 $did =~ s/[^0-9]//g;
2709 $error = _provision( 'FS::svc_phone',
2710 [qw(phonenum countrycode)],
2711 [qw(phonenum countrycode)],
2713 'pkgnum' => $p->{'pkgnum'},
2714 'svcpart' => $p->{'svcpart'},
2716 'countrycode' => $p->{'countrycode'},
2717 'session_id' => $p->{'session_id'},
2720 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2722 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2727 warn "provision_pbx called\n"
2730 warn "provision_pbx calling _provision\n"
2732 _provision( 'FS::svc_pbx',
2733 [qw(id title max_extensions max_simultaneous ip_addr)],
2734 [qw(id title max_extensions max_simultaneous ip_addr)],
2740 sub provision_acct {
2742 warn "provision_acct called\n"
2745 return { 'error' => gettext('passwords_dont_match') }
2746 if $p->{'_password'} ne $p->{'_password2'};
2747 return { 'error' => gettext('empty_password') }
2748 unless length($p->{'_password'});
2750 if ($p->{'domsvc'}) {
2751 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2752 qw ( svcpart pkgnum ) );
2753 return { 'error' => gettext('invalid_domain') }
2754 unless ($domains{$p->{'domsvc'}});
2757 warn "provision_acct calling _provision\n"
2759 _provision( 'FS::svc_acct',
2760 [qw(username _password domsvc)],
2761 [qw(username _password domsvc)],
2767 sub provision_external {
2769 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2770 _provision( 'FS::svc_external',
2778 sub provision_forward {
2780 _provision( 'FS::svc_forward',
2781 ['srcsvc','src','dstsvc','dst'],
2788 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2789 warn "_provision called for $class\n"
2792 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2793 return { 'error' => $session } if $context eq 'error';
2795 my $search = { 'custnum' => $custnum };
2796 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2797 my $cust_main = qsearchs('cust_main', $search )
2798 or return { 'error' => "unknown custnum $custnum" };
2800 my $pkgnum = $p->{'pkgnum'};
2802 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2804 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2805 'pkgnum' => $pkgnum,
2807 or return { 'error' => "unknown pkgnum $pkgnum" };
2809 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2811 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2812 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2814 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2815 if $class ne 'FS::'. $part_svc->svcdb;
2817 warn "creating $class record\n"
2819 my $svc_x = $class->new( {
2820 'pkgnum' => $p->{'pkgnum'},
2821 'svcpart' => $p->{'svcpart'},
2822 map { $_ => $p->{$_} } @$fields
2825 my %insert_args = ();
2826 #i shouldn't be a special case here (pass an option or something)
2827 if ( $class eq 'FS::svc_phone'
2828 && grep length($p->{$_}), @location_editable_fields
2831 $insert_args{'cust_location'} = new FS::cust_location {
2832 map { $_ => $p->{$_} } @location_editable_fields
2836 warn "inserting $class record\n"
2838 my $error = $svc_x->insert(%insert_args);
2841 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2843 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2846 my $return = { 'svc' => $part_svc->svc,
2848 map { $_ => $svc_x->get($_) } @$return_fields
2850 warn "_provision returning ". Dumper($return). "\n"
2859 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2860 return { 'error' => $session } if $context eq 'error';
2862 my $search = { 'custnum' => $custnum };
2863 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2864 my $cust_main = qsearchs('cust_main', $search )
2865 or return { 'error' => "unknown custnum $custnum" };
2867 my $pkgnum = $p->{'pkgnum'};
2869 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2870 'pkgnum' => $pkgnum,
2872 or return { 'error' => "unknown pkgnum $pkgnum" };
2874 my $svcpart = $p->{'svcpart'};
2876 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2877 'svcpart' => $svcpart, } )
2878 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2879 my $part_svc = $pkg_svc->part_svc;
2881 my $conf = new FS::Conf;
2884 'svc' => $part_svc->svc,
2885 'svcdb' => $part_svc->svcdb,
2886 'pkgnum' => $pkgnum,
2887 'svcpart' => $svcpart,
2888 'custnum' => $custnum,
2890 'security_phrase' => 0, #XXX !
2891 'svc_acct_pop' => [], #XXX !
2893 'init_popstate' => '',
2898 small_custview( $cust_main, $conf->config('countrydefault') ),
2902 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2903 && $ret->{'svcdb'} eq 'svc_phone') {
2904 $ret->{'svcnum'} = $p->{'svcnum'};
2905 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2906 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2907 $ret->{'email'} = $svc_phone->email;
2908 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2912 if ($ret->{'svcdb'} eq 'svc_forward') {
2913 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2919 sub unprovision_svc {
2922 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2923 return { 'error' => $session } if $context eq 'error';
2925 my $search = { 'custnum' => $custnum };
2926 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2927 my $cust_main = qsearchs('cust_main', $search )
2928 or return { 'error' => "unknown custnum $custnum" };
2930 my $svcnum = $p->{'svcnum'};
2932 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2933 or return { 'error' => "unknown svcnum $svcnum" };
2935 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2936 unless $cust_svc->cust_pkg->custnum == $custnum;
2938 my $conf = new FS::Conf;
2940 return { 'svc' => $cust_svc->part_svc->svc,
2941 'error' => $cust_svc->cancel,
2943 small_custview( $cust_main, $conf->config('countrydefault') ),
2948 sub myaccount_passwd {
2950 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2951 return { 'error' => $session } if $context eq 'error';
2953 return { 'error' => "New passwords don't match." }
2954 if $p->{'new_password'} ne $p->{'new_password2'};
2956 return { 'error' => 'Enter new password' }
2957 unless length($p->{'new_password'});
2959 #my $search = { 'custnum' => $custnum };
2960 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2961 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2962 my $search = " AND custnum = $1";
2963 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2965 my $svc_acct = qsearchs( {
2966 'table' => 'svc_acct',
2967 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2968 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2969 'LEFT JOIN cust_main USING ( custnum ) ',
2970 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2971 'extra_sql' => $search, #important
2973 or return { 'error' => "Service not found" };
2977 my $conf = new FS::Conf;
2979 return { 'error' => 'Incorrect current password.' }
2980 if ( exists($p->{'old_password'})
2981 || $conf->exists('selfservice-password_change_oldpass')
2983 && ! $svc_acct->check_password($p->{'old_password'});
2985 # should move password length checks into is_password_allowed
2986 $error = 'Password too short.'
2987 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2988 $error = 'Password too long.'
2989 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2991 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
2992 || $svc_acct->set_password($p->{'new_password'})
2993 || $svc_acct->replace();
2995 #regular pw change in self-service should change contact pw too, otherwise its
2996 #way too confusing. hell its confusing they're separate at all, but alas.
2997 #need to support the "ISP provides email that's used as a contact email" case
2999 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3000 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3001 custnum => $custnum,
3002 selfservice_access => 'Y',
3006 #svc_acct was successful but this one returns an error? "shouldn't happen"
3007 $error ||= $contact->change_password($p->{'new_password'});
3010 my($label, $value) = $svc_acct->cust_svc->label;
3012 return { 'error' => $error,
3022 my $info = skin_info($p);
3024 my $conf = new FS::Conf;
3025 my $verification = $conf->config('selfservice-password_reset_verification')
3026 or return { %$info, 'error' => 'Password resets disabled' };
3031 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3033 $contact = FS::contact->by_selfservice_email($p->{'email'});
3036 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3037 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3040 #also look for an svc_acct, otherwise it would be super confusing
3042 my($username, $domain) = split('@', $p->{'email'});
3043 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3044 if ( $svc_domain ) {
3045 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3046 'domsvc' => $svc_domain->svcnum }
3049 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3050 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3052 #precaution: don't change svc_acct password not part of the same
3053 # customer as contact
3054 $svc_acct = '' if ! $cust_pkg
3055 || $cust_pkg->custnum != $cust_main->custnum;
3060 return { %$info, 'error' => 'Email address not found' }
3061 unless $contact || $svc_acct;
3063 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3065 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3066 or return { %$info, 'error' => 'Account not found' };
3068 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3069 'domsvc' => $svc_domain->svcnum }
3071 or return { %$info, 'error' => 'Account not found' };
3073 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3074 or return { %$info, 'error' => 'Account not found' };
3076 $cust_main = $cust_pkg->cust_main;
3080 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3081 if ! $cust_main && $verification ne 'email';
3084 'email' => sub { 1; },
3086 my( $p, $cust_main ) = @_;
3087 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3088 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3091 my( $p, $cust_main ) = @_;
3092 my $cust_pay = qsearchs({
3093 'table' => 'cust_pay',
3094 'hashref' => { 'custnum' => $cust_main->custnum },
3095 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3099 $p->{'amount'} == $cust_pay->paid;
3102 my( $p, $cust_main ) = @_;
3103 $p->{'zip'} eq $cust_main->zip
3104 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3108 foreach my $verify ( split(',', $verification) ) {
3110 &{ $verify{$verify} }( $p, $cust_main )
3111 or return { %$info, 'error' => 'Account not found' };
3115 #okay, we're verified
3119 my $error = $contact->send_reset_email(
3120 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3124 return { %$info, 'error' => $error }; #????
3127 } elsif ( $svc_acct ) {
3129 #create a unique session
3131 my $reset_session = {
3132 'svcnum' => $svc_acct->svcnum,
3133 'agentnum' => $svc_acct->cust_main->agentnum,
3136 my $timeout = '1 hour'; #?
3138 my $reset_session_id;
3140 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3141 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3144 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3148 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3149 $cust_main->agentnum);
3150 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3151 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3153 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3154 my $error = $msg_template->send( 'cust_main' => $cust_main,
3155 'object' => $svc_acct,
3156 'substitutions' => {
3157 'session_id' => $reset_session_id,
3161 return { %$info, 'error' => $error }; #????
3166 return { %$info, 'error' => '' };
3169 sub check_reset_passwd {
3172 my $conf = new FS::Conf;
3173 my $verification = $conf->config('selfservice-password_reset_verification')
3174 or return { 'error' => 'Password resets disabled' };
3176 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3177 or return { 'error' => "Can't resume session" }; #better error message
3179 if ( $reset_session->{'svcnum'} ) {
3181 my $svcnum = $reset_session->{'svcnum'};
3183 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3184 or return { 'error' => "Service not found" };
3186 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3187 my $info = skin_info($p);
3191 'session_id' => $p->{'session_id'},
3192 'username' => $svc_acct->username,
3195 } elsif ( $reset_session->{'contactnum'} ) {
3197 my $contactnum = $reset_session->{'contactnum'};
3199 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3200 or return { 'error' => "Contact not found" };
3202 my @contact_email = $contact->contact_email;
3203 return { 'error' => 'No contact email' } unless @contact_email;
3205 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3206 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3207 if scalar(@cust_contact) == 1;
3208 my $info = skin_info($p);
3212 'session_id' => $p->{'session_id'},
3213 'email' => $contact_email[0]->email, #the first?
3218 return { 'error' => 'No svcnum or contactnum in session' }; #??
3224 sub process_reset_passwd {
3227 my $conf = new FS::Conf;
3228 my $verification = $conf->config('selfservice-password_reset_verification')
3229 or return { 'error' => 'Password resets disabled' };
3231 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3232 or return { 'error' => "Can't resume session" }; #better error message
3237 if ( $reset_session->{'svcnum'} ) {
3239 my $svcnum = $reset_session->{'svcnum'};
3241 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3242 or return { 'error' => "Service not found" };
3244 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3245 $info ||= skin_info($p);
3250 if ( $reset_session->{'contactnum'} ) {
3252 my $contactnum = $reset_session->{'contactnum'};
3254 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3255 or return { 'error' => "Contact not found" };
3257 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3258 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3259 if scalar(@cust_contact) == 1;
3260 $info ||= skin_info($p);
3264 return { %$info, 'error' => "New passwords don't match." }
3265 if $p->{'new_password'} ne $p->{'new_password2'};
3267 return { %$info, 'error' => 'Enter new password' }
3268 unless length($p->{'new_password'});
3272 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3273 || $svc_acct->set_password($p->{'new_password'})
3274 || $svc_acct->replace();
3276 return { %$info, 'error' => $error } if $error;
3278 #my($label, $value) = $svc_acct->cust_svc->label;
3279 #return { 'error' => $error,
3280 # #'label' => $label,
3281 # #'value' => $value,
3288 my $error = $contact->change_password($p->{'new_password'});
3290 return { %$info, 'error' => $error }; # if $error;
3294 #password changed ,so remove session, don't want it reused
3295 _cache->remove($p->{'session_id'});
3297 return { %$info, 'error' => '' };
3303 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3304 return { 'error' => $session } if $context eq 'error';
3307 if ( $session->{'pkgnum'} ) {
3309 #tickets for specific service with pkg-balances on
3310 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3311 'pkgnum' => $session->{'pkgnum'} })
3312 or return { 'error' => 'unknown package' };
3313 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3314 push @tickets, $cust_svc->tickets( $p->{status} );
3319 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3320 or return { 'error' => "unknown custnum $custnum" };
3322 @tickets = $cust_main->tickets( $p->{status} );
3325 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3326 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3327 my $conf = new FS::Conf;
3328 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3332 ($a->{'_selfservice_priority'} eq '') <=>
3333 ($b->{'_selfservice_priority'} eq '')
3336 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3342 +{ tickets => \@tickets };
3349 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3350 return { 'error' => $session } if $context eq 'error';
3352 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3353 FS::TicketSystem->init();
3355 my $conf = new FS::Conf;
3356 my $queue = $p->{'queue'}
3357 || $conf->config('ticket_system-selfservice_queueid')
3358 || $conf->config('ticket_system-default_queueid');
3360 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3361 my $err_or_ticket = FS::TicketSystem->create_ticket(
3362 '', #create RT session based on FS CurrentUser (fs_selfservice)
3364 'custnum' => $custnum,
3365 'svcnum' => $session->{'svcnum'},
3366 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3369 if ( ref($err_or_ticket) ) {
3370 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3372 return { 'error' => '',
3373 'ticket_id' => $err_or_ticket->id,
3376 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3378 return { 'error' => $err_or_ticket };
3386 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3387 return { 'error' => $session } if $context eq 'error';
3389 return { error => 'requested format not implemented' }
3390 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3392 my $conf = new FS::Conf;
3393 my $age_threshold = 0;
3394 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3395 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3397 my $search = { 'custnum' => $custnum };
3398 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3399 my $cust_main = qsearchs('cust_main', $search )
3400 or return { 'error' => "unknown custnum $custnum" };
3402 # does it make more sense to just run one sql query for this instead of all the
3403 # insanity below? would increase performance greately for large data sets?
3405 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3406 my @part_svc = $cust_pkg->part_svc;
3407 foreach my $part_svc ( @part_svc ) {
3408 if($part_svc->svcdb eq 'svc_phone'){
3409 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3410 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3411 push @svc_phone, $cust_pkg_svc->svc_x
3412 if $cust_pkg_svc->date_inserted >= $age_threshold;
3420 my($xls_r,$xls_c) = (0,0);
3423 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3424 if($p->{'format'} eq 'csv') {
3425 $csv = new Text::CSV_XS { 'always_quote' => 1,
3428 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3429 $content .= $csv->string;
3431 elsif($p->{'format'} eq 'xls') {
3432 my $XLS1 = new IO::Scalar \$content;
3433 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3434 or return { 'error' => "Error opening .xls file: $!" };
3435 $xls = $xls_workbook->add_worksheet('DIDs');
3436 foreach ( @fields ) {
3437 $xls->write(0,$xls_c++,$_);
3442 foreach my $svc_phone ( @svc_phone ) {
3443 my @cols = map { $svc_phone->$_ } @fields;
3444 if($p->{'format'} eq 'csv') {
3445 return { 'error' => 'Unable to create CSV' }
3446 unless $csv->combine(@cols);
3447 $content .= $csv->string;
3449 elsif($p->{'format'} eq 'xls') {
3452 $xls->write($xls_r,$xls_c++,$_);
3458 $xls_workbook->close() if $p->{'format'} eq 'xls';
3460 { content => $content, format => $p->{'format'}, };
3465 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3466 return { 'error' => $session } if $context eq 'error';
3468 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3469 # FS::TicketSystem->init();
3470 # return { 'error' => 'get_ticket configuration error' }
3471 # if $FS::TicketSystem::system ne 'RT_Internal';
3473 # check existence and ownership as part of this
3474 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3475 my $rt_session = FS::TicketSystem->session('');
3476 my $Ticket = FS::TicketSystem->get_ticket_object(
3478 ticket_id => $p->{'ticket_id'},
3481 return { 'error' => 'ticket not found' } if !$Ticket;
3483 if ( length( $p->{'subject'} || '' ) ) {
3485 if ( $p->{'subject'} ne $Ticket->Subject ) {
3486 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3487 return { 'error' => "unable to set subject: $msg" } if !$val;
3491 if(length($p->{'reply'})) {
3492 my @err_or_res = FS::TicketSystem->correspond_ticket(
3494 'ticket_id' => $p->{'ticket_id'},
3495 'content' => $p->{'reply'},
3498 return { 'error' => 'unable to reply to ticket' }
3499 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3502 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3503 my $err_or_ticket = FS::TicketSystem->get_ticket(
3505 'ticket_id' => $p->{'ticket_id'},
3508 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3509 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3511 return { 'error' => $err_or_ticket };
3514 my @custs = @{$err_or_ticket->{'custs'}};
3515 my @txns = @{$err_or_ticket->{'txns'}};
3518 # superseded by check in get_ticket_object
3519 #return { 'error' => 'invalid ticket requested' }
3520 #unless grep($_ eq $custnum, @custs);
3522 foreach my $txn ( @txns ) {
3523 push @filtered_txns, $txn
3524 if ($txn->{'type'} eq 'EmailRecord'
3525 || $txn->{'type'} eq 'Correspond'
3526 || $txn->{'type'} eq 'Create');
3529 warn "$me get_ticket: successful: \n"
3531 return { 'error' => '',
3532 'transactions' => \@filtered_txns,
3533 'ticket_fields' => $err_or_ticket->{'fields'},
3534 'ticket_id' => $p->{'ticket_id'},
3538 sub adjust_ticket_priority {
3540 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3541 return { 'error' => $session } if $context eq 'error';
3543 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3544 # FS::TicketSystem->init;
3545 my $ss_priority = FS::TicketSystem->selfservice_priority;
3547 return { 'error' => 'adjust_ticket_priority configuration error' }
3548 if $FS::TicketSystem::system ne 'RT_Internal'
3551 my $values = $p->{'values'}; #hashref, id => priority value
3554 foreach my $id (keys %$values) {
3555 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3556 my $Ticket = FS::TicketSystem->get_ticket_object('',
3558 'custnum' => $custnum,
3561 $ticket_error{$id} = 'ticket not found';
3565 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3566 # We're not going to implement it for RT_External.
3567 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3568 my $new_value = $values->{$id};
3569 next if $old_value eq $new_value;
3571 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3573 # AddCustomFieldValue works fine (replacing any existing value) if it's
3574 # a single-valued custom field, which it should be. If it's not, you're
3575 # doing something wrong.
3577 if ( length($new_value) ) {
3578 ($val, $msg) = $Ticket->AddCustomFieldValue(
3579 Field => $ss_priority,
3580 Value => $new_value,
3584 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3585 Field => $ss_priority,
3586 Value => $old_value,
3590 $ticket_error{$id} = $msg if !$val;
3591 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3593 return { 'error' => '',
3594 'ticket_error' => \%ticket_error,
3595 %{ customer_info($p) } # send updated customer info back
3601 sub _custoragent_session_custnum {
3604 my($context, $session, $custnum);
3605 if ( $p->{'session_id'} ) {
3607 $context = 'customer';
3608 $session = _cache->get($p->{'session_id'})
3609 or return ( 'error' => "Can't resume session" ); #better error message
3610 $custnum = $session->{'custnum'};
3612 } elsif ( $p->{'agent_session_id'} ) {
3615 my $agent_cache = new FS::ClientAPI_SessionCache( {
3616 'namespace' => 'FS::ClientAPI::Agent',
3618 $session = $agent_cache->get($p->{'agent_session_id'})
3619 or return ( 'error' => "Can't resume session" ); #better error message
3620 $custnum = $p->{'custnum'};
3624 return ( 'error' => "Can't resume session" ); #better error message
3627 ($context, $session, $custnum);