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;
49 use FS::cust_location;
51 # for code organization
52 use FS::ClientAPI::MyAccount::contact;
53 use FS::ClientAPI::MyAccount::quotation;
56 $me = '[FS::ClientAPI::MyAccount]';
58 use vars qw( @cust_main_editable_fields @location_editable_fields );
59 @cust_main_editable_fields = qw(
60 first last company daytime night fax mobile
62 payby payinfo payname paystart_month paystart_year payissue payip
63 ss paytype paystate stateid stateid_state
65 @location_editable_fields = qw(
66 address1 address2 city county state zip country
70 BEGIN { #preload to reduce time customer_info takes
71 if ( $FS::TicketSystem::system ) {
72 warn "$me: initializing ticket system\n" if $DEBUG;
73 FS::TicketSystem->init();
78 $cache ||= new FS::ClientAPI_SessionCache( {
79 'namespace' => 'FS::ClientAPI::MyAccount',
86 my($context, $session, $custnum) = _custoragent_session_custnum($p);
87 #return { 'error' => $session } if $context eq 'error';
90 if ( $context eq 'customer' ) {
92 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
95 $sth->execute($custnum) or die $sth->errstr;
97 $agentnum = $sth->fetchrow_arrayref->[0]
98 or die "no agentnum for custnum $custnum";
100 #} elsif ( $context eq 'agent' ) {
101 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
104 $p->{'agentnum'} = $agentnum;
106 my $conf = new FS::Conf;
108 #false laziness w/Signup.pm
110 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
112 if ( $skin_info_cache_agent ) {
114 warn "$me loading cached skin info for agentnum $agentnum\n"
119 warn "$me populating skin info cache for agentnum $agentnum\n"
122 $skin_info_cache_agent = {
123 'agentnum' => $agentnum,
124 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
125 qw( company_name date_format ) ),
126 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
127 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
128 text_color link_color vlink_color hlink_color alink_color
129 font title_color title_align title_size menu_bgcolor menu_fontsize
132 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
133 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
134 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
136 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
137 qw( title_left_image title_right_image
138 menu_top_image menu_body_image menu_bottom_image
141 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
142 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
143 qw( head body_header body_footer company_address ) ),
144 'money_char' => $conf->config("money_char") || '$',
145 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
148 services.php Services
149 services.php My Services
150 services_new.php Order a new service
153 personal.php Personal Information
154 password.php Change Password
157 payment_cc.php Credit Card Payment
158 payment_ach.php Electronic Check Payment
159 payment_paypal.php PayPal Payment
160 payment_webpay.php Webpay Payments
163 usage_data.php Data usage
164 usage_cdr.php Call usage
166 tickets.php Help Desk
167 tickets.php Open Tickets
168 tickets_resolved.php Resolved Tickets
169 ticket_create.php Create a new ticket
177 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
181 #{ %$skin_info_cache_agent };
182 $skin_info_cache_agent;
189 my $conf = new FS::Conf;
193 'phone_login' => $conf->exists('selfservice_server-phone_login'),
194 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
195 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
196 'banner_image_md5' =>
197 md5_hex($conf->config_binary('selfservice-login_banner_image')),
204 sub login_banner_image {
206 my $conf = new FS::Conf;
207 my $image = $conf->config_binary('selfservice-login_banner_image');
209 'md5' => md5_hex($image),
214 #false laziness w/FS::ClientAPI::passwd::passwd
218 my $conf = new FS::Conf;
222 if ( $p->{'domain'} eq 'svc_phone'
223 && $conf->exists('selfservice_server-phone_login') ) {
225 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
226 return { error => 'Number not found.' } unless $svc_phone;
229 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
230 #return { error => 'Only primary user may log in.' }
231 # if $conf->exists('selfservice_server-primary_only')
232 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
234 return { error => 'Incorrect PIN.' }
235 unless $svc_phone->check_pin($p->{'password'});
239 } elsif ( $p->{email}
240 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
243 return { error => 'Incorrect contact password.' }
244 unless $contact->authenticate_password($p->{'password'});
246 $session->{'contactnum'} = $contact->contactnum;
248 $session->{'custnum'} = $contact->custnum;
252 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
254 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
255 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
257 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
258 'domsvc' => $svc_domain->svcnum, }
261 if ( $conf->exists('selfservice_server-login_svcpart') ) {
262 my @svcpart = $conf->config('selfservice_server-login_svcpart');
263 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
264 scalar( grep( $_ eq $svcpart, @svcpart ) );
269 if ( $conf->exists('selfservice_server-primary_only') ) {
272 my $cust_svc = $_->cust_svc;
273 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
274 == $cust_svc->svcpart
279 return { error => 'User not found.' } unless @svc_acct;
281 #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
283 my $svc_acct = $svc_acct[0];
285 if ( $conf->exists('selfservice_server-login_svcpart') ) {
286 my @svcpart = $conf->config('selfservice_server-login_svcpart');
287 my $svcpart = $svc_acct->cust_svc->svcpart;
288 return { error => 'Invalid user.' }
289 unless grep($_ eq $svcpart, @svcpart);
292 return { error => 'Incorrect password.' }
293 unless $svc_acct->check_password($p->{'password'});
301 $session->{'svcnum'} = $svc_x->svcnum;
303 my $cust_svc = $svc_x->cust_svc;
304 my $cust_pkg = $cust_svc->cust_pkg;
306 my $cust_main = $cust_pkg->cust_main;
307 $session->{'custnum'} = $cust_main->custnum;
308 if ( $conf->exists('pkg-balances') ) {
309 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
310 $cust_main->ncancelled_pkgs;
311 $session->{'pkgnum'} = $cust_pkg->pkgnum
312 if scalar(@cust_pkg) > 1;
316 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
317 #return { error => 'Only primary user may log in.' }
318 # if $conf->exists('selfservice_server-primary_only')
319 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
320 my $part_pkg = $cust_pkg->part_pkg;
321 return { error => 'Only primary user may log in.' }
322 if $conf->exists('selfservice_server-primary_only')
323 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
329 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
330 } until ( ! defined _cache->get($session_id) ); #just in case
332 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
333 _cache->set( $session_id, $session, $timeout );
335 return { 'error' => '',
336 'session_id' => $session_id,
342 my $skin_info = skin_info($p);
343 if ( $p->{'session_id'} ) {
344 _cache->remove($p->{'session_id'});
345 return { %$skin_info, 'error' => '' };
347 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
354 my($context, $session, $custnum) = _custoragent_session_custnum($p);
355 return { 'error' => $session } if $context eq 'error';
357 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
358 or return { 'error' => "Service not found" };
360 $session->{'svcnum'} = $svc_acct->svcnum;
362 my $conf = new FS::Conf;
363 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
364 _cache->set( $p->{'session_id'}, $session, $timeout );
366 return { 'error' => '' };
370 sub payment_gateway {
372 # takes a cust_main and a cust_payby entry, returns the payment_gateway
373 my $conf = new FS::Conf;
374 my $cust_main = shift;
375 my $cust_payby = shift;
376 my $gatewaynum = $conf->config('selfservice-payment_gateway');
378 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
379 die "configured gatewaynum $gatewaynum not found!" if !$pg;
383 return '' if ! FS::payby->realtime($cust_payby);
384 my $pg = $cust_main->agent->payment_gateway(
385 'method' => FS::payby->payby2bop($cust_payby),
395 my $conf = new FS::Conf;
397 my $info = skin_info($p);
399 use vars qw( $cust_paybys ); #cache for performance
400 unless ( $cust_paybys ) {
402 my %cust_paybys = map { $_ => 1 }
403 map { FS::payby->payby2payment($_) }
404 $conf->config('signup_server-payby');
406 $cust_paybys = [ keys %cust_paybys ];
409 $info->{'cust_paybys'} = $cust_paybys;
411 my($context, $session, $custnum) = _custoragent_session_custnum($p);
412 return { 'error' => $session } if $context eq 'error';
414 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
415 or return { 'error' => "unknown custnum $custnum" };
417 $info->{'hide_payment_fields'} = [
419 my $pg = payment_gateway($cust_main, $_);
420 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
421 } @{ $info->{cust_paybys} }
424 $info->{'self_suspend_reason'} =
425 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
427 $info->{'edit_ticket_subject'} =
428 $conf->exists('ticket_system-selfservice_edit_subject') &&
429 $cust_main->edit_subject;
431 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
433 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
436 'custnum' => $custnum,
437 'access_pkgnum' => $session->{'pkgnum'},
438 'access_svcnum' => $session->{'svcnum'},
445 my($context, $session, $custnum) = _custoragent_session_custnum($p);
446 return { 'error' => $session } if $context eq 'error';
450 my $conf = new FS::Conf;
451 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
453 # if ( $FS::TicketSystem::system ) {
454 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
455 # FS::TicketSystem->init();
458 if ( $custnum ) { #customer record
460 %return = ( %return, %{ customer_info_short($p) } );
462 #redundant with customer_info_short, but we need it for several things below
463 my $search = { 'custnum' => $custnum };
464 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
465 my $cust_main = qsearchs('cust_main', $search )
466 or return { 'error' => "unknown custnum $custnum" };
468 my $list_tickets = list_tickets($p);
469 $return{'tickets'} = $list_tickets->{'tickets'};
471 if ( $session->{'pkgnum'} ) {
472 #XXX open invoices in the pkg-balances case
474 $return{'money_char'} = $conf->config("money_char") || '$';
477 invnum => $_->invnum,
478 date => time2str("%b %o, %Y", $_->_date),
480 charged => $_->charged,
482 } $cust_main->open_cust_bill;
483 $return{open_invoices} = \@open;
485 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
486 my $sth = dbh->prepare($sql) or die dbh->errstr;
487 $sth->execute($custnum) or die $sth->errstr;
488 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
489 $return{'last_invoice_date_pretty'} =
490 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
493 #customer_info_short always has nobalance on..
494 $return{small_custview} =
495 small_custview( $cust_main,
496 $return{countrydefault},
497 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
500 $return{has_ship_address} = $cust_main->has_ship_address;
501 $return{status} = $cust_main->status;
502 $return{statuscolor} = $cust_main->statuscolor;
504 # compatibility: some places in selfservice use this to determine
505 # if there's a ship address
506 if ( $return{has_ship_address} ) {
507 $return{ship_last} = $cust_main->last;
508 $return{ship_first} = $cust_main->first;
511 if (scalar($conf->config('support_packages'))) {
512 my @support_services = ();
513 foreach ($cust_main->support_services) {
514 my $seconds = $_->svc_x->seconds || 0;
515 my $time_remaining = (($seconds < 0) ? '-' : '' ).
516 int(abs($seconds)/3600)."h".
517 sprintf("%02d",(abs($seconds)%3600)/60)."m";
518 my $cust_pkg = $_->cust_pkg;
521 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
522 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
523 push @support_services, { svcnum => $_->svcnum,
524 time => $time_remaining,
529 $return{support_services} = \@support_services;
532 if ( $conf->config('prepayment_discounts-credit_type') ) {
534 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
537 } elsif ( $session->{'svcnum'} ) { #no customer record
539 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
540 or die "unknown svcnum";
541 $return{name} = $svc_acct->email;
545 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
549 return { 'error' => '',
550 'custnum' => $custnum,
556 sub customer_info_short {
559 my($context, $session, $custnum) = _custoragent_session_custnum($p);
560 return { 'error' => $session } if $context eq 'error';
564 my $conf = new FS::Conf;
566 if ( $custnum ) { #customer record
568 my $search = { 'custnum' => $custnum };
569 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
570 my $cust_main = qsearchs('cust_main', $search )
571 or return { 'error' => "unknown custnum $custnum" };
573 $return{display_custnum} = $cust_main->display_custnum;
575 if ( $session->{'pkgnum'} ) {
576 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
577 #next_bill_date from cust_pkg?
579 $return{balance} = $cust_main->balance;
580 $return{next_bill_date} = $cust_main->next_bill_date;
581 $return{next_bill_date_pretty} =
582 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
585 $return{balance_pretty} = money_pretty($return{balance});
587 $return{countrydefault} = scalar($conf->config('countrydefault'));
589 $return{small_custview} =
590 small_custview( $cust_main,
591 $return{countrydefault},
595 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
597 $return{payby} = $cust_main->payby;
599 #none of these are terribly expensive if we want 'em...
600 for (@cust_main_editable_fields) {
601 $return{$_} = $cust_main->get($_);
603 #maybe a little more expensive, but it should be cached by now
604 for (@location_editable_fields) {
605 $return{$_} = $cust_main->bill_location->get($_);
606 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
609 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
610 $return{payinfo} = $cust_main->paymask;
611 @return{'month', 'year'} = $cust_main->paydate_monthyear;
614 my @invoicing_list = $cust_main->invoicing_list;
615 $return{'invoicing_list'} =
616 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
617 $return{'postal_invoicing'} =
618 0 < ( grep { $_ eq 'POST' } @invoicing_list );
620 if ( $session->{'svcnum'} ) {
621 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
622 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
623 $return{'svcnum'} = $session->{'svcnum'};
626 } elsif ( $session->{'svcnum'} ) { #no customer record
628 #uuh, not supproted yet... die?
629 return { 'error' => 'customer_info_short not yet supported as agent' };
633 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
637 return { 'error' => '',
638 'custnum' => $custnum,
643 sub billing_history {
646 my($context, $session, $custnum) = _custoragent_session_custnum($p);
647 return { 'error' => $session } if $context eq 'error';
649 return { 'error' => 'No customer' } unless $custnum;
651 my $search = { 'custnum' => $custnum };
652 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
653 my $cust_main = qsearchs('cust_main', $search )
654 or return { 'error' => "unknown custnum $custnum" };
658 if ( $session->{'pkgnum'} ) {
659 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
660 #next_bill_date from cust_pkg?
661 return { 'error' => 'No history for package' };
664 $return{balance} = $cust_main->balance;
665 $return{balance_pretty} = money_pretty($return{balance});
666 $return{next_bill_date} = $cust_main->next_bill_date;
667 $return{next_bill_date_pretty} =
668 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
671 my $conf = new FS::Conf;
673 $return{'history'} = [
674 $cust_main->payment_history(
675 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
680 $return{'money_char'} = $conf->config("money_char") || '$',
688 my $session = _cache->get($p->{'session_id'})
689 or return { 'error' => "Can't resume session" }; #better error message
691 my $custnum = $session->{'custnum'}
692 or return { 'error' => "no customer record" };
694 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
695 or return { 'error' => "unknown custnum $custnum" };
697 my $new = new FS::cust_main { $cust_main->hash };
699 $new->set( $_ => $p->{$_} )
700 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
702 if ( exists($p->{address1}) ) {
703 my $bill_location = FS::cust_location->new({
704 map { $_ => $p->{$_} } @location_editable_fields
706 # if this is unchanged from before, cust_main::replace will ignore it
707 $new->set('bill_location' => $bill_location);
710 if ( exists($p->{ship_address1}) ) {
711 my $ship_location = FS::cust_location->new({
712 map { $_ => $p->{"ship_$_"} } @location_editable_fields
714 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
715 # Selfservice unfortunately tries to indicate "same as billing
716 # address" by sending all fields empty. Did this ever work?
717 $ship_location = $cust_main->bill_location;
719 $new->set('ship_location' => $ship_location);
721 # but if it hasn't been passed in at all, leave ship_location alone--
722 # DON'T change it to match bill_location.
725 if (exists($p->{'payby'})) {
726 $p->{'payby'} =~ /^([A-Z]{4})$/
727 or return { 'error' => "illegal_payby " . $p->{'payby'} };
731 my $conf = new FS::Conf;
733 if ( $payby =~ /^(CARD|DCRD)$/ ) {
735 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
737 if ( $new->payinfo eq $cust_main->paymask ) {
738 $new->payinfo($cust_main->payinfo);
739 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
741 $new->payinfo($p->{'payinfo'});
742 return { 'error' => 'CVV2 is required' }
743 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
744 $new->paycvv( $p->{'paycvv'} )
747 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
749 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
752 $p->{'payinfo1'} =~ /^([\dx]+)$/
753 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
755 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
756 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
758 $payinfo = $payinfo1. '@'. $payinfo2;
760 $new->payinfo( ($payinfo eq $cust_main->paymask)
761 ? $cust_main->payinfo
765 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
767 } elsif ( $payby =~ /^(BILL)$/ ) {
769 } elsif ( $payby ) { #notyet ready
770 return { 'error' => "unknown payby $payby" };
774 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
775 #false laziness with httemplate/edit/process/cust_main.cgi
776 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
777 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
779 @invoicing_list = $cust_main->invoicing_list;
782 my $error = $new->replace($cust_main, \@invoicing_list);
783 return { 'error' => $error } if $error;
786 return { 'error' => '' };
791 my $session = _cache->get($p->{'session_id'})
792 or return { 'error' => "Can't resume session" }; #better error message
798 my $conf = new FS::Conf;
799 use vars qw($payment_info); #cache for performance
800 unless ( $payment_info ) {
802 my %states = map { $_->state => 1 }
803 qsearch('cust_main_county', {
804 'country' => $conf->config('countrydefault') || 'US'
807 my %cust_paybys = map { $_ => 1 }
808 map { FS::payby->payby2payment($_) }
809 $conf->config('signup_server-payby');
811 my @cust_paybys = keys %cust_paybys;
815 #list all counties/states/countries
816 'cust_main_county' =>
817 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
819 #shortcut for one-country folks
821 [ sort { $a cmp $b } keys %states ],
823 'card_types' => card_types(),
825 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
826 'require_cvv' => $conf->exists('selfservice-require_cvv'),
827 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
829 'paytypes' => [ @FS::cust_main::paytypes ],
831 'paybys' => [ $conf->config('signup_server-payby') ],
832 'cust_paybys' => \@cust_paybys,
834 'stateid_label' => FS::Msgcat::_gettext('stateid'),
835 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
837 'show_ss' => $conf->exists('show_ss'),
838 'show_stateid' => $conf->exists('show_stateid'),
839 'show_paystate' => $conf->exists('show_bankstate'),
841 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
843 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
852 my %return = %$payment_info;
854 my $custnum = $session->{'custnum'};
856 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
857 or return { 'error' => "unknown custnum $custnum" };
859 $return{'hide_payment_fields'} = [
861 my $pg = payment_gateway($cust_main, $_);
862 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
863 } @{ $return{cust_paybys} }
866 $return{balance} = $cust_main->balance; #XXX pkg-balances?
868 $return{payname} = $cust_main->payname
869 || ( $cust_main->first. ' '. $cust_main->get('last') );
871 $return{$_} = $cust_main->bill_location->get($_)
872 for qw(address1 address2 city state zip);
874 $return{payby} = $cust_main->payby;
875 $return{stateid_state} = $cust_main->stateid_state;
877 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
878 $return{card_type} = cardtype($cust_main->payinfo);
879 $return{payinfo} = $cust_main->paymask;
881 @return{'month', 'year'} = $cust_main->paydate_monthyear;
885 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
886 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
887 $return{payinfo1} = $payinfo1;
888 $return{payinfo2} = $payinfo2;
889 $return{paytype} = $cust_main->paytype;
890 $return{paystate} = $cust_main->paystate;
891 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
894 if ( $conf->config('prepayment_discounts-credit_type') ) {
896 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
899 #doubleclick protection
901 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
902 $return{paybatch} = $return{payunique}; #back compat
904 return { 'error' => '',
910 #some false laziness with httemplate/process/payment.cgi - look there for
911 #ACH and CVV support stuff
913 sub validate_payment {
916 my $session = _cache->get($p->{'session_id'})
917 or return { 'error' => "Can't resume session" }; #better error message
919 my $custnum = $session->{'custnum'};
921 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
922 or return { 'error' => "unknown custnum $custnum" };
924 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
925 or return { 'error' => gettext('illegal_amount') };
927 return { error => 'Amount must be greater than 0' } unless $amount > 0;
929 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
930 #changing the hidden form values
931 my $conf = new FS::Conf;
932 my $fee_display = $conf->config('selfservice_process-display') || 'add';
933 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
934 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
935 if ( $fee_display eq 'add'
937 and ! $fee_skip_first || scalar($cust_main->cust_pay)
940 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
941 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
944 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
945 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
946 my $discount_term = $1;
948 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
949 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
952 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
953 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
956 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
957 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
960 $payunique = $paybatch if ! length($payunique) && length($paybatch);
962 $p->{'payby'} ||= 'CARD';
963 $p->{'payby'} =~ /^([A-Z]{4})$/
964 or return { 'error' => "illegal_payby " . $p->{'payby'} };
967 #false laziness w/process/payment.cgi
970 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
972 $p->{'payinfo1'} =~ /^([\dx]+)$/
973 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
975 $p->{'payinfo2'} =~ /^([\dx]+)$/
976 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
978 $payinfo = $payinfo1. '@'. $payinfo2;
980 $payinfo = $cust_main->payinfo
981 if $cust_main->paymask eq $payinfo;
983 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
985 $payinfo = $p->{'payinfo'};
989 #more intelligent matching will be needed here if you change
990 #card_masking_method and don't remove existing paymasks
991 if ( $cust_main->paymask eq $payinfo ) {
992 $payinfo = $cust_main->payinfo;
997 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
998 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1002 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1003 return { 'error' => gettext('unknown_card_type') }
1004 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1006 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1007 if ( cardtype($payinfo) eq 'American Express card' ) {
1008 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1009 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1012 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1013 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1016 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1017 return { 'error' => 'CVV2 is required' };
1018 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1019 return { 'error' => 'CVV2 is required' };
1023 die "unknown payby $payby";
1026 my %payby2fields = (
1027 'CARD' => [ qw( paystart_month paystart_year payissue payip
1028 address1 address2 city state zip country ) ],
1029 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1033 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1036 'cust_main' => $cust_main, #XXX or just custnum??
1037 'amount' => sprintf('%.2f', $amount),
1039 'payinfo' => $payinfo,
1040 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1041 'card_type' => $card_type,
1042 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1043 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1044 'month' => $p->{'month'},
1045 'year' => $p->{'year'},
1046 'payname' => $payname,
1047 'payunique' => $payunique,
1048 'paybatch' => $paybatch,
1049 'paycvv' => $paycvv,
1050 'payname' => $payname,
1051 'discount_term' => $discount_term,
1052 'pkgnum' => $session->{'pkgnum'},
1053 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1063 my $validate = validate_payment($p);
1064 return $validate if $validate->{'error'};
1066 my $conf = new FS::Conf;
1067 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1068 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1070 +{ map { $_=>$validate->{$_} }
1071 qw( card_type paymask payname paydate_pretty month year amount
1072 address1 address2 city state zip country
1078 sub process_stored_payment {
1081 my $session_id = $p->{'session_id'};
1083 my $payment_info = _cache->get( "payment_$session_id" )
1084 or return { 'error' => "Can't resume session" }; #better error message
1086 do_process_payment($payment_info);
1090 sub process_payment {
1093 my $payment_info = validate_payment($p);
1094 return $payment_info if $payment_info->{'error'};
1096 do_process_payment($payment_info);
1100 sub do_process_payment {
1101 my $validate = shift;
1103 my $cust_main = $validate->{'cust_main'};
1105 my $amount = delete $validate->{'amount'};
1108 my $payby = delete $validate->{'payby'};
1110 if ( $validate->{'save'} ) {
1111 my $new = new FS::cust_main { $cust_main->hash };
1112 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1113 $new->set( $_ => $validate->{$_} )
1114 foreach qw( payname paystart_month paystart_year payissue payip );
1115 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1117 my $bill_location = FS::cust_location->new({
1118 map { $_ => $validate->{$_} }
1119 qw(address1 address2 city state country zip)
1121 $new->set('bill_location' => $bill_location);
1122 # but don't allow the service address to change this way.
1124 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1125 $new->set( $_ => $validate->{$_} )
1126 foreach qw( payname payip paytype paystate
1127 stateid stateid_state );
1128 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1130 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1131 $new->set( 'paydate' => $validate->{'paydate'} );
1132 my $error = $new->replace($cust_main);
1134 #no, this causes customers to process their payments again
1135 #return { 'error' => $error };
1136 #XXX just warn verosely for now so i can figure out how these happen in
1137 # the first place, eventually should redirect them to the "change
1138 #address" page but indicate if the payment processed?
1139 delete($validate->{'payinfo'}); #don't want to log this!
1140 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1141 "NEW: ". Dumper($new)."\n".
1142 "OLD: ". Dumper($cust_main)."\n".
1143 "PACKET: ". Dumper($validate)."\n";
1149 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1153 'paynum_ref' => \$paynum,
1156 return { 'error' => $error } if $error;
1158 #no error, so order the fee package if applicable...
1159 my $conf = new FS::Conf;
1160 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1161 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1163 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1165 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1167 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1168 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1171 #and generate an invoice for it now too
1172 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1173 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1178 $cust_main->apply_payments;
1181 my $receipt_html = '';
1183 # currently supported for realtime CC only; send receipt data to SS
1184 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1187 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1190 <TD ALIGN="right">Payment#</TD>
1191 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1195 <TD ALIGN="right">Date</TD>
1197 <TD BGCOLOR="#FFFFFF"><B>! .
1198 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1204 <TD ALIGN="right">Amount</TD>
1205 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1210 <TD ALIGN="right">Payment method</TD>
1211 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1224 'amount' => sprintf('%.2f', $cust_pay->paid),
1225 'date' => $cust_pay->_date,
1226 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1227 'time_pretty' => time2str('%T', $cust_pay->_date),
1228 'auth_num' => $cust_pay->auth,
1229 'order_num' => $cust_pay->order_number,
1230 'receipt_html' => $receipt_html,
1237 'receipt_html' => '',
1244 sub realtime_collect {
1247 my $session = _cache->get($p->{'session_id'})
1248 or return { 'error' => "Can't resume session" }; #better error message
1250 my $custnum = $session->{'custnum'};
1252 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1253 or return { 'error' => "unknown custnum $custnum" };
1256 if ( $p->{'amount'} ) {
1257 $amount = $p->{'amount'};
1259 elsif ( $session->{'pkgnum'} ) {
1260 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1263 $amount = $cust_main->balance;
1266 my $error = $cust_main->realtime_collect(
1267 'method' => $p->{'method'},
1268 'amount' => $amount,
1269 'pkgnum' => $session->{'pkgnum'},
1270 'session_id' => $p->{'session_id'},
1274 return { 'error' => $error } unless ref( $error );
1276 return { 'error' => '', amount => $amount, %$error };
1279 sub start_thirdparty {
1281 my $session = _cache->get($p->{'session_id'})
1282 or return { 'error' => "Can't resume session" }; #better error message
1283 my $custnum = $session->{'custnum'};
1284 my $cust_main = FS::cust_main->by_key($custnum);
1286 my $amount = $p->{'amount'}
1287 or return { error => 'no amount' };
1289 my $result = $cust_main->create_payment(
1290 'method' => $p->{'method'},
1291 'amount' => $p->{'amount'},
1292 'pkgnum' => $session->{'pkgnum'},
1293 'session_id' => $p->{'session_id'},
1296 if ( ref($result) ) { # hashref or error
1299 return { error => $result };
1303 sub finish_thirdparty {
1305 my $session_id = delete $p->{'session_id'};
1306 my $session = _cache->get($session_id)
1307 or return { 'error' => "Can't resume session" };
1308 my $custnum = $session->{'custnum'};
1309 my $cust_main = FS::cust_main->by_key($custnum);
1311 if ( $p->{_cancel} ) {
1312 # customer backed out of making a payment
1313 return $cust_main->cancel_payment( $session_id );
1315 my $result = $cust_main->execute_payment( $session_id, %$p );
1316 if ( ref($result) ) {
1319 return { error => $result };
1323 sub process_payment_order_pkg {
1326 my $hr = process_payment($p);
1327 return $hr if $hr->{'error'};
1332 sub process_payment_order_renew {
1335 my $hr = process_payment($p);
1336 return $hr if $hr->{'error'};
1341 sub process_prepay {
1345 my $session = _cache->get($p->{'session_id'})
1346 or return { 'error' => "Can't resume session" }; #better error message
1350 my $custnum = $session->{'custnum'};
1352 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1353 or return { 'error' => "unknown custnum $custnum" };
1355 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1356 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1364 return { 'error' => $error } if $error;
1366 return { 'error' => '',
1367 'amount' => $amount,
1368 'seconds' => $seconds,
1369 'duration' => duration_exact($seconds),
1370 'upbytes' => $upbytes,
1371 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1372 'downbytes' => $downbytes,
1373 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1374 'totalbytes'=> $totalbytes,
1375 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1382 my $session = _cache->get($p->{'session_id'})
1383 or return { 'error' => "Can't resume session" }; #better error message
1385 my $custnum = $session->{'custnum'};
1387 my $invnum = $p->{'invnum'};
1389 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1390 'custnum' => $custnum } )
1391 or return { 'error' => "Can't find invnum" };
1395 return { 'error' => '',
1396 'invnum' => $invnum,
1397 'invoice_text' => join('', $cust_bill->print_text ),
1398 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1405 my $session = _cache->get($p->{'session_id'})
1406 or return { 'error' => "Can't resume session" }; #better error message
1408 my $custnum = $session->{'custnum'};
1410 my $invnum = $p->{'invnum'};
1412 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1413 'custnum' => $custnum } )
1414 or return { 'error' => "Can't find invnum" };
1418 return { 'error' => '',
1419 'invnum' => $invnum,
1420 'invoice_pdf' => $cust_bill->print_pdf({
1421 'unsquelch_cdr' => 1,
1422 'locale' => $p->{'locale'},
1428 sub legacy_invoice {
1430 my $session = _cache->get($p->{'session_id'})
1431 or return { 'error' => "Can't resume session" }; #better error message
1433 my $custnum = $session->{'custnum'};
1435 my $legacyinvnum = $p->{'legacyinvnum'};
1438 'legacyinvnum' => $legacyinvnum,
1439 'custnum' => $custnum,
1442 my $legacy_cust_bill =
1443 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1444 || qsearchs('legacy_cust_bill', \%hash )
1445 or return { 'error' => "Can't find legacyinvnum" };
1449 return { 'error' => '',
1450 'legacyinvnum' => $legacyinvnum,
1451 'legacyid' => $legacy_cust_bill->legacyid,
1452 'invoice_html' => $legacy_cust_bill->content_html,
1457 sub legacy_invoice_pdf {
1459 my $session = _cache->get($p->{'session_id'})
1460 or return { 'error' => "Can't resume session" }; #better error message
1462 my $custnum = $session->{'custnum'};
1464 my $legacyinvnum = $p->{'legacyinvnum'};
1466 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1467 'legacyinvnum' => $legacyinvnum,
1468 'custnum' => $custnum,
1469 }) or return { 'error' => "Can't find legacyinvnum" };
1473 return { 'error' => '',
1474 'legacyinvnum' => $legacyinvnum,
1475 'legacyid' => $legacy_cust_bill->legacyid,
1476 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1484 #sessioning for this? how do we get the session id to the backend invoice
1485 # template so it can add it to the link, blah
1488 if ( $p->{'invnum'} ) {
1489 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1490 or return { 'error' => 'unknown invnum' };
1491 $agentnum = $cust_bill->cust_main->agentnum;
1494 my $templatename = $p->{'template'} || $p->{'templatename'};
1496 #false laziness-ish w/view/cust_bill-logo.cgi
1498 my $conf = new FS::Conf;
1499 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1500 $templatename = "_$1";
1505 my $filename = "logo$templatename.png";
1507 return { 'error' => '',
1508 'logo' => $conf->config_binary($filename, $agentnum),
1509 'content_type' => 'image/png', #should allow gif, jpg too
1516 my $session = _cache->get($p->{'session_id'})
1517 or return { 'error' => "Can't resume session" }; #better error message
1519 my $custnum = $session->{'custnum'};
1521 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1522 or return { 'error' => "unknown custnum $custnum" };
1524 my $conf = new FS::Conf;
1526 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1528 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1533 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1534 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1535 my $owed = $_->owed;
1537 +{ 'invnum' => $_->invnum,
1538 '_date' => $_->_date,
1539 'date' => time2str("%b %o, %Y", $_->_date),
1540 'date_short' => time2str("%m-%d-%Y", $_->_date),
1541 'previous' => sprintf('%.2f', ($_->previous)[0]),
1542 'charged' => sprintf('%.2f', $_->charged),
1543 'owed' => sprintf('%.2f', $owed),
1544 'balance' => sprintf('%.2f', $balance),
1545 'lastpay' => @payments_and_credits
1546 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1552 return { 'error' => '',
1553 'balance' => $cust_main->balance,
1554 'money_char' => $conf->config("money_char") || '$',
1555 'invoices' => $invoices,
1556 'legacy_invoices' => [
1558 +{ 'legacyinvnum' => $_->legacyinvnum,
1559 'legacyid' => $_->legacyid,
1560 '_date' => $_->_date,
1561 'date' => time2str("%b %o, %Y", $_->_date),
1562 'date_short' => time2str("%m-%d-%Y", $_->_date),
1563 'charged' => sprintf('%.2f', $_->charged),
1564 'has_content' => ( length($_->content_pdf)
1565 || length($_->content_html) ),
1575 my $session = _cache->get($p->{'session_id'})
1576 or return { 'error' => "Can't resume session" }; #better error message
1578 my $custnum = $session->{'custnum'};
1580 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1581 or return { 'error' => "unknown custnum $custnum" };
1583 my @errors = $cust_main->cancel( 'quiet'=>1 );
1585 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1587 return { 'error' => $error };
1594 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1595 return { 'error' => $session } if $context eq 'error';
1597 my $search = { 'custnum' => $custnum };
1598 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1599 my $cust_main = qsearchs('cust_main', $search )
1600 or return { 'error' => "unknown custnum $custnum" };
1602 my $conf = new FS::Conf;
1603 my $immutable = $conf->exists('selfservice_immutable-package');
1605 # the duplication below is necessary:
1606 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1607 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1608 # non-backwards-compatible change breaking the software of anyone using the API
1609 # instead of the stock selfservice
1610 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1611 if( $conf->exists('selfservice_server-view-wholesale') ) {
1612 return { 'svcnum' => $session->{'svcnum'},
1613 'custnum' => $custnum,
1614 'cust_pkg' => [ map {
1616 immutable => $immutable,
1617 part_pkg => [ map $_->hashref, $_->part_pkg ],
1619 [ map $_->hashref, $_->available_part_svc ],
1621 [ map { my $ref = { $_->hash,
1622 label => [ $_->label ],
1624 $ref->{_password} = $_->svc_x->_password
1625 if $context eq 'agent'
1626 && $conf->exists('agent-showpasswords')
1627 && $_->part_svc->svcdb eq 'svc_acct';
1632 } $cust_main->cust_pkg
1635 small_custview( $cust_main, $conf->config('countrydefault') ),
1636 'wholesale_view' => 1,
1637 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1638 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1639 'lnp' => $conf->exists('svc_phone-lnp'),
1643 { 'svcnum' => $session->{'svcnum'},
1644 'custnum' => $custnum,
1645 'cust_pkg' => [ map {
1646 my $primary_cust_svc = $_->primary_cust_svc;
1649 immutable => $immutable,
1650 pkg_label => $_->pkg_locale,
1651 status => $_->status,
1652 statuscolor => $_->statuscolor,
1654 [ map { $_->hashref }
1655 grep { $_->selfservice_access ne 'hidden' }
1656 $_->available_part_svc
1659 [ map { my $ref = { $_->hash,
1660 label => [ $_->label ],
1662 $ref->{_password} = $_->svc_x->_password
1663 if $context eq 'agent'
1664 && $conf->exists('agent-showpasswords')
1665 && $_->part_svc->svcdb eq 'svc_acct';
1666 $ref->{svchash} = { $_->svc_x->hash } if
1667 $_->part_svc->svcdb eq 'svc_phone';
1668 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1669 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1672 grep { $_->part_svc->selfservice_access ne 'hidden' }
1677 ? { $primary_cust_svc->hash,
1678 label => [ $primary_cust_svc->label ],
1679 finger => $primary_cust_svc->svc_x->finger, #uuh
1680 $primary_cust_svc->part_svc->hash,
1684 } $cust_main->ncancelled_pkgs
1687 small_custview( $cust_main, $conf->config('countrydefault') ),
1688 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1696 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1697 return { 'error' => $session } if $context eq 'error';
1699 my $conf = new FS::Conf;
1701 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1702 my $search = { 'custnum' => $custnum };
1703 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1704 my $cust_main = qsearchs('cust_main', $search )
1705 or return { 'error' => "unknown custnum $custnum" };
1707 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1708 if ( ! $pkgnum && $p->{'svcnum'} ) {
1709 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1710 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1714 my @cust_pkg_usage = ();
1715 foreach my $cust_pkg ( $p->{'ncancelled'}
1716 ? $cust_main->ncancelled_pkgs
1717 : $cust_main->unsuspended_pkgs ) {
1718 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1719 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1720 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1723 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1726 foreach (@cust_pkg_usage) {
1727 my $part = $_->part_pkg_usage;
1728 my $tag = $part->description . ($part->shared ? 1 : 0);
1729 my $row = $usage_pools{$tag}
1730 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1731 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1732 $row->[2] += $part->minutes; # minutes total
1734 } # otherwise just leave them empty
1736 if ( $p->{'svcdb'} ) {
1737 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1739 : ref($p->{'svcdb'}) eq 'ARRAY'
1740 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1741 : { $p->{'svcdb'} => 1 };
1742 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1745 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1748 my @svcs; # stuff to return to the client
1749 foreach my $cust_svc (@cust_svc) {
1750 my $svc_x = $cust_svc->svc_x;
1751 my($label, $value) = $cust_svc->label;
1752 my $part_svc = $cust_svc->part_svc;
1753 my $svcdb = $part_svc->svcdb;
1754 my $cust_pkg = $cust_svc->cust_pkg;
1755 my $part_pkg = $cust_pkg->part_pkg;
1758 'svcnum' => $cust_svc->svcnum,
1759 'display_svcnum' => $cust_svc->display_svcnum,
1763 'pkg_label' => $cust_pkg->pkg_locale,
1764 'pkg_status' => $cust_pkg->status,
1765 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1768 # would it make sense to put this in a svc_* method?
1770 if ( $svcdb eq 'svc_acct' ) {
1771 foreach (qw(username email finger seconds)) {
1772 $hash{$_} = $svc_x->$_;
1778 'upbytes' => display_bytecount($svc_x->upbytes),
1779 'downbytes' => display_bytecount($svc_x->downbytes),
1780 'totalbytes' => display_bytecount($svc_x->totalbytes),
1782 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1783 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1784 'recharge_upbytes' =>
1785 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1786 'recharge_downbytes' =>
1787 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1788 'recharge_totalbytes' =>
1789 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1794 } elsif ( $svcdb eq 'svc_dsl' ) {
1796 $hash{'phonenum'} = $svc_x->phonenum;
1797 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1798 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1799 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1802 $hash{'name'} = $cust_main->name;
1804 # no usage to hide here
1806 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1808 # could potentially show lots of things...
1809 $hash{'outbound'} = 1;
1810 $hash{'inbound'} = 0;
1811 if ( $svcdb eq 'svc_phone' ) {
1812 if ( $part_pkg->plan eq 'voip_inbound' ) {
1813 $hash{'outbound'} = 0;
1814 $hash{'inbound'} = 1;
1815 } elsif ( $part_pkg->option('selfservice_inbound_format')
1816 or $conf->config('selfservice-default_inbound_cdr_format')
1818 $hash{'inbound'} = 1;
1821 foreach (qw(inbound outbound)) {
1822 # hmm...we can't filter by status here, because there might
1823 # not be cdr_terminations at all. have to go by date.
1824 # find all since the last bill date.
1825 # XXX cdr types? we are going to need them.
1827 my $sum_cdr = $svc_x->sum_cdrs(
1828 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1829 'begin' => ($cust_pkg->last_bill || 0),
1831 'disable_charged_party' => 1,
1833 $hash{$_} = $sum_cdr->hashref;
1836 } # not hiding usage
1840 } # foreach $cust_svc
1843 'svcnum' => $session->{'svcnum'},
1844 'custnum' => $custnum,
1845 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1846 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1849 map { $usage_pools{$_} }
1853 'hide_usage' => $hide_usage,
1858 sub _customer_svc_x {
1859 my($custnum, $svcnum, $table) = (shift, shift, shift);
1860 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1862 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1863 my $search = " AND custnum = $1";
1864 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1867 'table' => ($table || 'svc_acct'),
1868 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1869 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1870 #'LEFT JOIN cust_main USING ( custnum ) ',
1871 'hashref' => $hashref,
1872 'extra_sql' => $search, #important
1877 sub svc_status_html {
1880 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1881 return { 'error' => $session } if $context eq 'error';
1883 #XXX only svc_dsl for now
1884 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1885 or return { 'error' => "Service not found" };
1887 my $html = $svc_x->getstatus_html;
1889 return { 'html' => $html };
1893 sub svc_status_hash {
1896 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1897 return { 'error' => $session } if $context eq 'error';
1899 #XXX only svc_acct for now
1900 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1901 or return { 'error' => "Service not found" };
1903 my ( $html, $hashref ) = $svc_x->export_getstatus;
1908 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1909 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1910 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1911 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1912 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1915 my( $p, $method ) = @_;
1917 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1918 return { 'error' => $session } if $context eq 'error';
1920 #XXX only svc_acct for now
1921 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1922 or return { 'error' => "Service not found" };
1924 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1926 my $error = $svc_x->$method($p); #$p? returns error?
1927 return { 'error' => $error } if $error;
1929 return {}; #? { 'error' => '' }
1933 sub acct_forward_info {
1936 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1937 return { 'error' => $session } if $context eq 'error';
1939 my $svc_forward = _customer_svc_x( $custnum,
1940 { 'srcsvc' => $p->{'svcnum'} },
1943 or return { 'error' => '',
1947 return { 'error' => '',
1948 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1953 sub process_acct_forward {
1955 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1956 return { 'error' => $session } if $context eq 'error';
1958 my $old = _customer_svc_x( $custnum,
1959 { 'srcsvc' => $p->{'svcnum'} },
1963 if ( $p->{'dst'} eq '' ) {
1965 my $error = $old->delete;
1966 return { 'error' => $error };
1968 return { 'error' => '' };
1971 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1972 'dst' => $p->{'dst'},
1977 $new->svcnum($old->svcnum);
1978 my $cust_svc = $old->cust_svc;
1979 $new->svcpart($old->svcpart);
1980 $new->pkgnuym($old->pkgnum);
1981 $error = $new->replace($old);
1983 my $conf = new FS::Conf;
1984 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1986 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1987 or return { 'error' => 'No service' }; #how would we even get here?
1989 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1991 $error = $new->insert;
1994 return { 'error' => $error };
1998 sub list_dsl_devices {
2001 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2002 return { 'error' => $session } if $context eq 'error';
2004 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2005 or return { 'error' => "Service not found" };
2008 'devices' => [ map {
2009 +{ 'mac_addr' => $_->mac_addr };
2010 } $svc_dsl->dsl_device
2016 sub add_dsl_device {
2019 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2020 return { 'error' => $session } if $context eq 'error';
2022 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2023 or return { 'error' => "Service not found" };
2025 return { 'error' => 'No MAC address supplied' }
2026 unless length($p->{'mac_addr'});
2028 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2029 'mac_addr' => scalar($p->{'mac_addr'}),
2031 my $error = $dsl_device->insert;
2032 return { 'error' => $error };
2036 sub delete_dsl_device {
2039 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2040 return { 'error' => $session } if $context eq 'error';
2042 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2043 or return { 'error' => "Service not found" };
2045 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2046 'mac_addr' => scalar($p->{'mac_addr'}),
2049 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2051 my $error = $dsl_device->delete;
2052 return { 'error' => $error };
2058 _usage_details( \&_port_graph, $p,
2059 'svcdb' => 'svc_port',
2064 my($svc_port, $begin, $end) = @_;
2066 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2067 push @usage, { 'png' => $pngOrError };
2071 sub _list_svc_usage {
2072 my($svc_acct, $begin, $end) = @_;
2074 foreach my $part_export (
2075 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2076 qw( sqlradius sqlradius_withdomain )
2078 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2083 sub list_svc_usage {
2084 _usage_details(\&_list_svc_usage, @_);
2087 sub _list_support_usage {
2088 my($svc_acct, $begin, $end) = @_;
2090 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2091 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2093 push @usage, { 'seconds' => $_->seconds,
2094 'support' => $_->support,
2095 '_date' => $_->_date,
2096 'id' => $_->transaction_id,
2097 'creator' => $_->creator,
2098 'subject' => $_->subject,
2099 'status' => $_->status,
2100 'ticketid' => $_->ticketid,
2106 sub list_support_usage {
2107 _usage_details(\&_list_support_usage, @_);
2110 sub _list_cdr_usage {
2111 # XXX CDR type support...
2112 # XXX any way to do a paged search on this?
2113 # we have to return the results all at once...
2114 my($svc_x, $begin, $end, %opt) = @_;
2115 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2119 'disable_charged_party' => 1,
2124 sub list_cdr_usage {
2126 _usage_details( \&_list_cdr_usage, $p );
2129 sub _usage_details {
2130 my($callback, $p, %opt) = @_;
2131 my $conf = FS::Conf->new;
2133 if ( $conf->exists('selfservice_hide-usage') ) {
2134 return { 'error' => 'Viewing usage is not allowed.' };
2137 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2138 return { 'error' => $session } if $context eq 'error';
2140 my $search = { 'svcnum' => $p->{'svcnum'} };
2141 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2143 my $cust_svc = qsearchs( 'cust_svc', $search );
2144 return { 'error' => 'No service selected in list_svc_usage' }
2147 my $svc_x = $cust_svc->svc_x;
2148 my $svcdb = $svc_x->table;
2149 my $cust_pkg = $cust_svc->cust_pkg;
2150 my $freq = $cust_pkg->part_pkg->freq;
2153 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2155 if ( $p->{inbound} ) {
2156 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2157 || $conf->config('selfservice-default_inbound_cdr_format')
2158 || 'source_default';
2159 $callback_opt{inbound} = 1;
2161 $format = $cust_pkg->part_pkg->option('selfservice_format')
2162 || $conf->config('selfservice-default_cdr_format')
2166 $callback_opt{format} = $format;
2167 $callback_opt{use_clid} = 1;
2168 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2171 my $start = $cust_pkg->setup;
2172 #my $end = $cust_pkg->bill; # or time?
2175 unless ( $p->{beginning} ) {
2176 $p->{beginning} = $cust_pkg->last_bill;
2177 $p->{ending} = $end;
2180 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2181 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2183 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2187 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2188 # ugly kludge, I know
2189 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2190 if (defined $delete_col) {
2191 delete($_->[$delete_col]) foreach ($header, @usage);
2195 #kinda false laziness with FS::cust_main::bill, but perhaps
2196 #we should really change this bit to DateTime and DateTime::Duration
2198 #change this bit to use Date::Manip? CAREFUL with timezones (see
2199 # mailing list archive)
2200 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2201 (localtime($p->{ending}) )[0,1,2,3,4,5];
2202 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2203 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2205 if ( $freq =~ /^\d+$/ ) {
2207 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2209 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2210 } elsif ( $freq =~ /^(\d+)w$/ ) {
2212 $nmday += $weeks * 7;
2213 $pmday -= $weeks * 7;
2214 } elsif ( $freq =~ /^(\d+)d$/ ) {
2218 } elsif ( $freq =~ /^(\d+)h$/ ) {
2223 return { 'error' => "unparsable frequency: ". $freq };
2226 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2227 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2231 'svcnum' => $p->{svcnum},
2232 'beginning' => $p->{beginning},
2233 'ending' => $p->{ending},
2234 'inbound' => $p->{inbound},
2235 'previous' => ($previous > $start) ? $previous : $start,
2236 'next' => ($next < $end) ? $next : $end,
2237 'header' => $header,
2245 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2246 return { 'error' => $session } if $context eq 'error';
2248 my $search = { 'custnum' => $custnum };
2249 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2250 my $cust_main = qsearchs('cust_main', $search )
2251 or return { 'error' => "unknown custnum $custnum" };
2253 my $status = $cust_main->status;
2255 my %order_pkg_options = ();
2256 if ( $p->{locationnum} > 0 ) {
2257 $order_pkg_options{locationnum} = delete($p->{locationnum});
2258 } elsif ( $p->{address1} ) {
2259 $order_pkg_options{'cust_location'} = new FS::cust_location {
2260 map { $_ => $p->{$_} }
2261 qw( address1 address2 city county state zip country )
2265 #false laziness w/ClientAPI/Signup.pm
2267 my $cust_pkg = new FS::cust_pkg ( {
2268 'custnum' => $custnum,
2269 'pkgpart' => $p->{'pkgpart'},
2270 'quantity' => $p->{'quantity'} || 1,
2272 my $error = $cust_pkg->check;
2273 return { 'error' => $error } if $error;
2276 unless ( $p->{'svcpart'} eq 'none' ) {
2280 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2282 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2283 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2284 $svcdb = $part_svc->svcdb;
2286 $svcdb = 'svc_acct';
2288 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2291 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2292 'svc_domain' => [ qw( domain ) ],
2293 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2294 'svc_external' => [ qw( id title ) ],
2295 'svc_pbx' => [ qw( id title ) ],
2298 my $svc_x = "FS::$svcdb"->new( {
2299 'svcpart' => $svcpart,
2300 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2303 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2306 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2307 my $acct_snarf = new FS::acct_snarf ( {
2308 'machine' => $p->{"snarf_machine$snarfnum"},
2309 'protocol' => $p->{"snarf_protocol$snarfnum"},
2310 'username' => $p->{"snarf_username$snarfnum"},
2311 '_password' => $p->{"snarf_password$snarfnum"},
2314 push @acct_snarf, $acct_snarf;
2316 $svc_x->child_objects( \@acct_snarf );
2319 my $y = $svc_x->setdefault; # arguably should be in new method
2320 return { 'error' => $y } if $y && !ref($y);
2322 $error = $svc_x->check;
2323 return { 'error' => $error } if $error;
2329 $error = $cust_main->order_pkg(
2330 'cust_pkg' => $cust_pkg,
2335 return { 'error' => $error } if $error;
2337 my $conf = new FS::Conf;
2338 if ( $conf->exists('signup_server-realtime') ) {
2340 my $bill_error = _do_bop_realtime( $cust_main, $status );
2343 $cust_pkg->cancel('quiet'=>1);
2346 $cust_pkg->reexport;
2350 $cust_pkg->reexport;
2353 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2355 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2362 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2363 return { 'error' => $session } if $context eq 'error';
2365 my $conf = new FS::Conf;
2366 my $immutable = $conf->exists('selfservice_immutable-package');
2367 return { 'error' => "Package modification disabled" } if $immutable;
2369 my $search = { 'custnum' => $custnum };
2370 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2371 my $cust_main = qsearchs('cust_main', $search )
2372 or return { 'error' => "unknown custnum $custnum" };
2374 my $status = $cust_main->status;
2375 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2376 or return { 'error' => "unknown package $p->{pkgnum}" };
2378 #if someone does need self-service package change of suspended packages,
2379 # figure out how to be more discriminating
2380 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2381 if $cust_pkg->status eq 'suspended';
2383 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2384 'quantity' => $p->{'quantity'} || 1,
2387 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2388 unless ref($err_or_cust_pkg);
2390 if ( $conf->exists('signup_server-realtime') ) {
2392 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2395 $err_or_cust_pkg->suspend;
2398 $err_or_cust_pkg->reexport;
2402 $err_or_cust_pkg->reexport;
2405 return { error => '', pkgnum => $cust_pkg->pkgnum };
2409 sub order_recharge {
2412 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2413 return { 'error' => $session } if $context eq 'error';
2415 my $search = { 'custnum' => $custnum };
2416 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2417 my $cust_main = qsearchs('cust_main', $search )
2418 or return { 'error' => "unknown custnum $custnum" };
2420 my $status = $cust_main->status;
2421 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2422 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2424 my $svc_x = $cust_svc->svc_x;
2425 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2428 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2429 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2430 recharge_totalbytes );
2431 my $amount = $part_pkg->option('recharge_amount', 1);
2433 my ($l, $v, $d) = $cust_svc->label; # blah
2434 my $pkg = "Recharge $v";
2436 my $bill_error = $cust_main->charge($amount, $pkg,
2437 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2438 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2439 $part_pkg->taxclass); #meh
2441 my $conf = new FS::Conf;
2442 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2444 $bill_error = _do_bop_realtime( $cust_main, $status );
2449 my $error = $svc_x->recharge (\%vhash);
2450 return { 'error' => $error } if $error;
2454 my $error = $bill_error;
2455 $error ||= $svc_x->recharge (\%vhash);
2456 return { 'error' => $error } if $error;
2459 return { error => '', svc => $cust_svc->part_svc->svc };
2463 sub _do_bop_realtime {
2464 my ($cust_main, $status, %opt) = @_;
2466 my $old_balance = $cust_main->balance;
2469 my $bill_error = $cust_main->bill(
2470 'return_bill' => \@cust_bill,
2473 $bill_error ||= $cust_main->apply_payments_and_credits;
2475 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2476 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2478 if ( $cust_main->balance > $old_balance
2479 && $cust_main->balance > 0
2480 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2481 || $status eq 'suspended'
2485 unless ( $opt{'no_invoice_void'} ) {
2487 #this used to apply a credit, but now we can void invoices...
2488 foreach my $cust_bill (@cust_bill) {
2489 my $voiderror = $cust_bill->void();
2490 warn "Error voiding cust bill after decline: $voiderror";
2495 return { 'error' => '_decline', 'bill_error' => $bill_error };
2504 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2505 return { 'error' => $session } if $context eq 'error';
2507 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2508 or return { 'error' => "unknown custnum $custnum" };
2510 my @cust_pkg = sort { $a->bill <=> $b->bill }
2511 grep { $_->part_pkg->freq ne '0' }
2512 $cust_main->ncancelled_pkgs;
2514 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2516 my $total = $cust_main->balance;
2519 my $bill = $_->bill;
2520 $total += $_->part_pkg->base_recur($_, \$bill);
2521 my $renew_date = $_->part_pkg->add_freq($_->bill);
2523 'pkgnum' => $_->pkgnum,
2524 'amount' => sprintf('%.2f', $total),
2525 'bill_date' => $_->bill,
2526 'bill_date_pretty' => time2str('%x', $_->bill),
2527 'renew_date' => $renew_date,
2528 'renew_date_pretty' => time2str('%x', $renew_date),
2529 'expire_date' => $_->expire,
2530 'expire_date_pretty' => time2str('%x', $_->expire),
2535 return { 'dates' => \@array };
2539 sub payment_info_renew_info {
2541 my $renew_info = renew_info($p);
2542 my $payment_info = payment_info($p);
2543 return { %$renew_info,
2551 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2552 return { 'error' => $session } if $context eq 'error';
2554 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2555 or return { 'error' => "unknown custnum $custnum" };
2557 my $date = $p->{'date'};
2561 #freeside-daily -n -d $date fs_daily $custnum
2562 $cust_main->bill_and_collect( 'time' => $date,
2563 'invoice_time' => $now,
2564 'actual_time' => $now,
2565 'check_freq' => '1d',
2568 return { 'error' => '' };
2574 my $session = _cache->get($p->{'session_id'})
2575 or return { 'error' => "Can't resume session" }; #better error message
2577 my $custnum = $session->{'custnum'};
2579 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2580 or return { 'error' => "unknown custnum $custnum" };
2582 my $conf = new FS::Conf;
2584 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2585 or return { 'error' => 'Permission denied' };
2587 my $pkgnum = $p->{'pkgnum'};
2589 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2590 'pkgnum' => $pkgnum, } )
2591 or return { 'error' => "unknown pkgnum $pkgnum" };
2593 my $error = $cust_pkg->suspend(reason => $reasonnum);
2594 return { 'error' => $error };
2600 my $session = _cache->get($p->{'session_id'})
2601 or return { 'error' => "Can't resume session" }; #better error message
2603 my $custnum = $session->{'custnum'};
2605 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2606 or return { 'error' => "unknown custnum $custnum" };
2608 my $pkgnum = $p->{'pkgnum'};
2610 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2611 'pkgnum' => $pkgnum, } )
2612 or return { 'error' => "unknown pkgnum $pkgnum" };
2614 my $error = $cust_pkg->cancel('quiet' => 1);
2615 return { 'error' => $error };
2619 sub provision_phone {
2622 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2624 #editing an existing phone number
2625 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2626 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2627 return { 'error' => $session } if $context eq 'error';
2629 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2630 return { 'error' => 'service not found' } unless $svc_phone;
2631 return { 'error' => 'invalid svcnum' }
2632 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2634 $svc_phone->email($p->{'email'})
2635 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2636 $svc_phone->forwarddst($p->{'forwarddst'})
2637 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2638 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2639 return { 'error' => $svc_phone->replace };
2643 unless ( $p->{'lnp'} ) {
2644 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2645 $p->{'lnp_status'} = "portingin";
2646 return _provision( 'FS::svc_phone',
2647 [qw(lnp_desired_due_date lnp_other_provider
2648 lnp_other_provider_account phonenum countrycode lnp_status)],
2649 [qw(phonenum countrycode)],
2655 # single DID order (the usual case)
2656 unless (scalar(@bulkdid)) {
2657 return _provision( 'FS::svc_phone',
2658 [qw(phonenum countrycode)],
2659 [qw(phonenum countrycode)],
2665 # bulk DID order case
2667 foreach my $did ( @bulkdid ) {
2668 $did =~ s/[^0-9]//g;
2669 $error = _provision( 'FS::svc_phone',
2670 [qw(phonenum countrycode)],
2671 [qw(phonenum countrycode)],
2673 'pkgnum' => $p->{'pkgnum'},
2674 'svcpart' => $p->{'svcpart'},
2676 'countrycode' => $p->{'countrycode'},
2677 'session_id' => $p->{'session_id'},
2680 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2682 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2687 warn "provision_pbx called\n"
2690 warn "provision_pbx calling _provision\n"
2692 _provision( 'FS::svc_pbx',
2693 [qw(id title max_extensions max_simultaneous ip_addr)],
2694 [qw(id title max_extensions max_simultaneous ip_addr)],
2700 sub provision_acct {
2702 warn "provision_acct called\n"
2705 return { 'error' => gettext('passwords_dont_match') }
2706 if $p->{'_password'} ne $p->{'_password2'};
2707 return { 'error' => gettext('empty_password') }
2708 unless length($p->{'_password'});
2710 if ($p->{'domsvc'}) {
2711 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2712 qw ( svcpart pkgnum ) );
2713 return { 'error' => gettext('invalid_domain') }
2714 unless ($domains{$p->{'domsvc'}});
2717 warn "provision_acct calling _provision\n"
2719 _provision( 'FS::svc_acct',
2720 [qw(username _password domsvc)],
2721 [qw(username _password domsvc)],
2727 sub provision_external {
2729 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2730 _provision( 'FS::svc_external',
2738 sub provision_forward {
2740 _provision( 'FS::svc_forward',
2741 ['srcsvc','src','dstsvc','dst'],
2748 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2749 warn "_provision called for $class\n"
2752 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2753 return { 'error' => $session } if $context eq 'error';
2755 my $search = { 'custnum' => $custnum };
2756 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2757 my $cust_main = qsearchs('cust_main', $search )
2758 or return { 'error' => "unknown custnum $custnum" };
2760 my $pkgnum = $p->{'pkgnum'};
2762 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2764 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2765 'pkgnum' => $pkgnum,
2767 or return { 'error' => "unknown pkgnum $pkgnum" };
2769 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2771 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2772 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2774 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2775 if $class ne 'FS::'. $part_svc->svcdb;
2777 warn "creating $class record\n"
2779 my $svc_x = $class->new( {
2780 'pkgnum' => $p->{'pkgnum'},
2781 'svcpart' => $p->{'svcpart'},
2782 map { $_ => $p->{$_} } @$fields
2785 my %insert_args = ();
2786 #i shouldn't be a special case here (pass an option or something)
2787 if ( $class eq 'FS::svc_phone'
2788 && grep length($p->{$_}), @location_editable_fields
2791 $insert_args{'cust_location'} = new FS::cust_location {
2792 map { $_ => $p->{$_} } @location_editable_fields
2796 warn "inserting $class record\n"
2798 my $error = $svc_x->insert(%insert_args);
2801 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2803 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2806 my $return = { 'svc' => $part_svc->svc,
2808 map { $_ => $svc_x->get($_) } @$return_fields
2810 warn "_provision returning ". Dumper($return). "\n"
2819 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2820 return { 'error' => $session } if $context eq 'error';
2822 my $search = { 'custnum' => $custnum };
2823 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2824 my $cust_main = qsearchs('cust_main', $search )
2825 or return { 'error' => "unknown custnum $custnum" };
2827 my $pkgnum = $p->{'pkgnum'};
2829 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2830 'pkgnum' => $pkgnum,
2832 or return { 'error' => "unknown pkgnum $pkgnum" };
2834 my $svcpart = $p->{'svcpart'};
2836 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2837 'svcpart' => $svcpart, } )
2838 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2839 my $part_svc = $pkg_svc->part_svc;
2841 my $conf = new FS::Conf;
2844 'svc' => $part_svc->svc,
2845 'svcdb' => $part_svc->svcdb,
2846 'pkgnum' => $pkgnum,
2847 'svcpart' => $svcpart,
2848 'custnum' => $custnum,
2850 'security_phrase' => 0, #XXX !
2851 'svc_acct_pop' => [], #XXX !
2853 'init_popstate' => '',
2858 small_custview( $cust_main, $conf->config('countrydefault') ),
2862 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2863 && $ret->{'svcdb'} eq 'svc_phone') {
2864 $ret->{'svcnum'} = $p->{'svcnum'};
2865 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2866 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2867 $ret->{'email'} = $svc_phone->email;
2868 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2872 if ($ret->{'svcdb'} eq 'svc_forward') {
2873 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2879 sub unprovision_svc {
2882 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2883 return { 'error' => $session } if $context eq 'error';
2885 my $search = { 'custnum' => $custnum };
2886 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2887 my $cust_main = qsearchs('cust_main', $search )
2888 or return { 'error' => "unknown custnum $custnum" };
2890 my $svcnum = $p->{'svcnum'};
2892 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2893 or return { 'error' => "unknown svcnum $svcnum" };
2895 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2896 unless $cust_svc->cust_pkg->custnum == $custnum;
2898 my $conf = new FS::Conf;
2900 return { 'svc' => $cust_svc->part_svc->svc,
2901 'error' => $cust_svc->cancel,
2903 small_custview( $cust_main, $conf->config('countrydefault') ),
2908 sub myaccount_passwd {
2910 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2911 return { 'error' => $session } if $context eq 'error';
2913 return { 'error' => "New passwords don't match." }
2914 if $p->{'new_password'} ne $p->{'new_password2'};
2916 return { 'error' => 'Enter new password' }
2917 unless length($p->{'new_password'});
2919 #my $search = { 'custnum' => $custnum };
2920 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2921 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2922 my $search = " AND custnum = $1";
2923 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2925 my $svc_acct = qsearchs( {
2926 'table' => 'svc_acct',
2927 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2928 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2929 'LEFT JOIN cust_main USING ( custnum ) ',
2930 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2931 'extra_sql' => $search, #important
2933 or return { 'error' => "Service not found" };
2937 my $conf = new FS::Conf;
2939 return { 'error' => 'Incorrect current password.' }
2940 if ( exists($p->{'old_password'})
2941 || $conf->exists('selfservice-password_change_oldpass')
2943 && ! $svc_acct->check_password($p->{'old_password'});
2945 $error = 'Password too short.'
2946 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2947 $error = 'Password too long.'
2948 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2950 $svc_acct->set_password($p->{'new_password'});
2951 $error ||= $svc_acct->replace();
2953 #regular pw change in self-service should change contact pw too, otherwise its
2954 #way too confusing. hell its confusing they're separate at all, but alas.
2955 #need to support the "ISP provides email that's used as a contact email" case
2957 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2958 if ( $contact && $contact->custnum == $custnum ) {
2959 #svc_acct was successful but this one returns an error? "shouldn't happen"
2960 $error ||= $contact->change_password($p->{'new_password'});
2963 my($label, $value) = $svc_acct->cust_svc->label;
2965 return { 'error' => $error,
2975 my $info = skin_info($p);
2977 my $conf = new FS::Conf;
2978 my $verification = $conf->config('selfservice-password_reset_verification')
2979 or return { %$info, 'error' => 'Password resets disabled' };
2984 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2986 $contact = FS::contact->by_selfservice_email($p->{'email'});
2988 $cust_main = $contact->cust_main if $contact;
2990 #also look for an svc_acct, otherwise it would be super confusing
2992 my($username, $domain) = split('@', $p->{'email'});
2993 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2994 if ( $svc_domain ) {
2995 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
2996 'domsvc' => $svc_domain->svcnum }
2999 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3000 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3002 #precaution: don't change svc_acct password not part of the same
3003 # customer as contact
3004 $svc_acct = '' if ! $cust_pkg
3005 || $cust_pkg->custnum != $cust_main->custnum;
3010 return { %$info, 'error' => 'Email address not found' }
3011 unless $contact || $svc_acct;
3013 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3015 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3016 or return { %$info, 'error' => 'Account not found' };
3018 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3019 'domsvc' => $svc_domain->svcnum }
3021 or return { %$info, 'error' => 'Account not found' };
3023 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3024 or return { %$info, 'error' => 'Account not found' };
3026 $cust_main = $cust_pkg->cust_main;
3031 'email' => sub { 1; },
3033 my( $p, $cust_main ) = @_;
3034 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3035 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3038 my( $p, $cust_main ) = @_;
3039 my $cust_pay = qsearchs({
3040 'table' => 'cust_pay',
3041 'hashref' => { 'custnum' => $cust_main->custnum },
3042 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3046 $p->{'amount'} == $cust_pay->paid;
3049 my( $p, $cust_main ) = @_;
3050 $p->{'zip'} eq $cust_main->zip
3051 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3055 foreach my $verify ( split(',', $verification) ) {
3057 &{ $verify{$verify} }( $p, $cust_main )
3058 or return { %$info, 'error' => 'Account not found' };
3062 #okay, we're verified
3066 my $error = $contact->send_reset_email(
3067 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3071 return { %$info, 'error' => $error }; #????
3074 } elsif ( $svc_acct ) {
3076 #create a unique session
3078 my $reset_session = {
3079 'svcnum' => $svc_acct->svcnum,
3080 'agentnum' => $svc_acct->cust_main->agentnum,
3083 my $timeout = '1 hour'; #?
3085 my $reset_session_id;
3087 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3088 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3091 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3095 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3096 $cust_main->agentnum);
3097 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3098 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3100 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3101 my $error = $msg_template->send( 'cust_main' => $cust_main,
3102 'object' => $svc_acct,
3103 'substitutions' => {
3104 'session_id' => $reset_session_id,
3108 return { %$info, 'error' => $error }; #????
3113 return { %$info, 'error' => '' };
3116 sub check_reset_passwd {
3119 my $conf = new FS::Conf;
3120 my $verification = $conf->config('selfservice-password_reset_verification')
3121 or return { 'error' => 'Password resets disabled' };
3123 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3124 or return { 'error' => "Can't resume session" }; #better error message
3126 if ( $reset_session->{'svcnum'} ) {
3128 my $svcnum = $reset_session->{'svcnum'};
3130 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3131 or return { 'error' => "Service not found" };
3133 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3134 my $info = skin_info($p);
3138 'session_id' => $p->{'session_id'},
3139 'username' => $svc_acct->username,
3142 } elsif ( $reset_session->{'contactnum'} ) {
3144 my $contactnum = $reset_session->{'contactnum'};
3146 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3147 or return { 'error' => "Contact not found" };
3149 my @contact_email = $contact->contact_email;
3150 return { 'error' => 'No contact email' } unless @contact_email;
3152 $p->{'agentnum'} = $contact->cust_main->agentnum;
3153 my $info = skin_info($p);
3157 'session_id' => $p->{'session_id'},
3158 'email' => $contact_email[0]->email, #the first?
3163 return { 'error' => 'No svcnum or contactnum in session' }; #??
3169 sub process_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
3182 if ( $reset_session->{'svcnum'} ) {
3184 my $svcnum = $reset_session->{'svcnum'};
3186 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3187 or return { 'error' => "Service not found" };
3189 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3190 $info ||= skin_info($p);
3195 if ( $reset_session->{'contactnum'} ) {
3197 my $contactnum = $reset_session->{'contactnum'};
3199 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3200 or return { 'error' => "Contact not found" };
3202 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3203 $info ||= skin_info($p);
3207 return { %$info, 'error' => "New passwords don't match." }
3208 if $p->{'new_password'} ne $p->{'new_password2'};
3210 return { %$info, 'error' => 'Enter new password' }
3211 unless length($p->{'new_password'});
3215 $svc_acct->set_password($p->{'new_password'});
3216 my $error = $svc_acct->replace();
3218 return { %$info, 'error' => $error } if $error;
3220 #my($label, $value) = $svc_acct->cust_svc->label;
3221 #return { 'error' => $error,
3222 # #'label' => $label,
3223 # #'value' => $value,
3230 my $error = $contact->change_password($p->{'new_password'});
3232 return { %$info, 'error' => $error }; # if $error;
3236 #password changed ,so remove session, don't want it reused
3237 _cache->remove($p->{'session_id'});
3239 return { %$info, 'error' => '' };
3245 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3246 return { 'error' => $session } if $context eq 'error';
3249 if ( $session->{'pkgnum'} ) {
3251 #tickets for specific service with pkg-balances on
3252 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3253 'pkgnum' => $session->{'pkgnum'} })
3254 or return { 'error' => 'unknown package' };
3255 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3256 push @tickets, $cust_svc->tickets( $p->{status} );
3261 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3262 or return { 'error' => "unknown custnum $custnum" };
3264 @tickets = $cust_main->tickets( $p->{status} );
3267 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3268 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3269 my $conf = new FS::Conf;
3270 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3274 ($a->{'_selfservice_priority'} eq '') <=>
3275 ($b->{'_selfservice_priority'} eq '')
3278 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3284 +{ tickets => \@tickets };
3291 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3292 return { 'error' => $session } if $context eq 'error';
3294 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3295 FS::TicketSystem->init();
3297 my $conf = new FS::Conf;
3298 my $queue = $p->{'queue'}
3299 || $conf->config('ticket_system-selfservice_queueid')
3300 || $conf->config('ticket_system-default_queueid');
3302 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3303 my $err_or_ticket = FS::TicketSystem->create_ticket(
3304 '', #create RT session based on FS CurrentUser (fs_selfservice)
3306 'custnum' => $custnum,
3307 'svcnum' => $session->{'svcnum'},
3308 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3311 if ( ref($err_or_ticket) ) {
3312 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3314 return { 'error' => '',
3315 'ticket_id' => $err_or_ticket->id,
3318 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3320 return { 'error' => $err_or_ticket };
3328 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3329 return { 'error' => $session } if $context eq 'error';
3331 return { error => 'requested format not implemented' }
3332 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3334 my $conf = new FS::Conf;
3335 my $age_threshold = 0;
3336 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3337 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3339 my $search = { 'custnum' => $custnum };
3340 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3341 my $cust_main = qsearchs('cust_main', $search )
3342 or return { 'error' => "unknown custnum $custnum" };
3344 # does it make more sense to just run one sql query for this instead of all the
3345 # insanity below? would increase performance greately for large data sets?
3347 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3348 my @part_svc = $cust_pkg->part_svc;
3349 foreach my $part_svc ( @part_svc ) {
3350 if($part_svc->svcdb eq 'svc_phone'){
3351 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3352 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3353 push @svc_phone, $cust_pkg_svc->svc_x
3354 if $cust_pkg_svc->date_inserted >= $age_threshold;
3362 my($xls_r,$xls_c) = (0,0);
3365 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3366 if($p->{'format'} eq 'csv') {
3367 $csv = new Text::CSV_XS { 'always_quote' => 1,
3370 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3371 $content .= $csv->string;
3373 elsif($p->{'format'} eq 'xls') {
3374 my $XLS1 = new IO::Scalar \$content;
3375 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3376 or return { 'error' => "Error opening .xls file: $!" };
3377 $xls = $xls_workbook->add_worksheet('DIDs');
3378 foreach ( @fields ) {
3379 $xls->write(0,$xls_c++,$_);
3384 foreach my $svc_phone ( @svc_phone ) {
3385 my @cols = map { $svc_phone->$_ } @fields;
3386 if($p->{'format'} eq 'csv') {
3387 return { 'error' => 'Unable to create CSV' }
3388 unless $csv->combine(@cols);
3389 $content .= $csv->string;
3391 elsif($p->{'format'} eq 'xls') {
3394 $xls->write($xls_r,$xls_c++,$_);
3400 $xls_workbook->close() if $p->{'format'} eq 'xls';
3402 { content => $content, format => $p->{'format'}, };
3407 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3408 return { 'error' => $session } if $context eq 'error';
3410 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3411 # FS::TicketSystem->init();
3412 # return { 'error' => 'get_ticket configuration error' }
3413 # if $FS::TicketSystem::system ne 'RT_Internal';
3415 # check existence and ownership as part of this
3416 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3417 my $rt_session = FS::TicketSystem->session('');
3418 my $Ticket = FS::TicketSystem->get_ticket_object(
3420 ticket_id => $p->{'ticket_id'},
3423 return { 'error' => 'ticket not found' } if !$Ticket;
3425 if ( length( $p->{'subject'} || '' ) ) {
3427 if ( $p->{'subject'} ne $Ticket->Subject ) {
3428 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3429 return { 'error' => "unable to set subject: $msg" } if !$val;
3433 if(length($p->{'reply'})) {
3434 my @err_or_res = FS::TicketSystem->correspond_ticket(
3436 'ticket_id' => $p->{'ticket_id'},
3437 'content' => $p->{'reply'},
3440 return { 'error' => 'unable to reply to ticket' }
3441 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3444 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3445 my $err_or_ticket = FS::TicketSystem->get_ticket(
3447 'ticket_id' => $p->{'ticket_id'},
3450 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3451 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3453 return { 'error' => $err_or_ticket };
3456 my @custs = @{$err_or_ticket->{'custs'}};
3457 my @txns = @{$err_or_ticket->{'txns'}};
3460 # superseded by check in get_ticket_object
3461 #return { 'error' => 'invalid ticket requested' }
3462 #unless grep($_ eq $custnum, @custs);
3464 foreach my $txn ( @txns ) {
3465 push @filtered_txns, $txn
3466 if ($txn->{'type'} eq 'EmailRecord'
3467 || $txn->{'type'} eq 'Correspond'
3468 || $txn->{'type'} eq 'Create');
3471 warn "$me get_ticket: successful: \n"
3473 return { 'error' => '',
3474 'transactions' => \@filtered_txns,
3475 'ticket_fields' => $err_or_ticket->{'fields'},
3476 'ticket_id' => $p->{'ticket_id'},
3480 sub adjust_ticket_priority {
3482 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3483 return { 'error' => $session } if $context eq 'error';
3485 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3486 # FS::TicketSystem->init;
3487 my $ss_priority = FS::TicketSystem->selfservice_priority;
3489 return { 'error' => 'adjust_ticket_priority configuration error' }
3490 if $FS::TicketSystem::system ne 'RT_Internal'
3493 my $values = $p->{'values'}; #hashref, id => priority value
3496 foreach my $id (keys %$values) {
3497 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3498 my $Ticket = FS::TicketSystem->get_ticket_object('',
3500 'custnum' => $custnum,
3503 $ticket_error{$id} = 'ticket not found';
3507 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3508 # We're not going to implement it for RT_External.
3509 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3510 my $new_value = $values->{$id};
3511 next if $old_value eq $new_value;
3513 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3515 # AddCustomFieldValue works fine (replacing any existing value) if it's
3516 # a single-valued custom field, which it should be. If it's not, you're
3517 # doing something wrong.
3519 if ( length($new_value) ) {
3520 ($val, $msg) = $Ticket->AddCustomFieldValue(
3521 Field => $ss_priority,
3522 Value => $new_value,
3526 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3527 Field => $ss_priority,
3528 Value => $old_value,
3532 $ticket_error{$id} = $msg if !$val;
3533 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3535 return { 'error' => '',
3536 'ticket_error' => \%ticket_error,
3537 %{ customer_info($p) } # send updated customer info back
3543 sub _custoragent_session_custnum {
3546 my($context, $session, $custnum);
3547 if ( $p->{'session_id'} ) {
3549 $context = 'customer';
3550 $session = _cache->get($p->{'session_id'})
3551 or return ( 'error' => "Can't resume session" ); #better error message
3552 $custnum = $session->{'custnum'};
3554 } elsif ( $p->{'agent_session_id'} ) {
3557 my $agent_cache = new FS::ClientAPI_SessionCache( {
3558 'namespace' => 'FS::ClientAPI::Agent',
3560 $session = $agent_cache->get($p->{'agent_session_id'})
3561 or return ( 'error' => "Can't resume session" ); #better error message
3562 $custnum = $p->{'custnum'};
3566 return ( 'error' => "Can't resume session" ); #better error message
3569 ($context, $session, $custnum);