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 0.35;
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 return '' if ! FS::payby->realtime($cust_payby);
377 my $pg = $cust_main->agent->payment_gateway(
378 'method' => FS::payby->payby2bop($cust_payby),
387 my $conf = new FS::Conf;
389 my $info = skin_info($p);
391 use vars qw( $cust_paybys ); #cache for performance
392 unless ( $cust_paybys ) {
394 my %cust_paybys = map { $_ => 1 }
395 map { FS::payby->payby2payment($_) }
396 $conf->config('signup_server-payby');
398 $cust_paybys = [ keys %cust_paybys ];
401 $info->{'cust_paybys'} = $cust_paybys;
403 my($context, $session, $custnum) = _custoragent_session_custnum($p);
404 return { 'error' => $session } if $context eq 'error';
406 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
407 or return { 'error' => "unknown custnum $custnum" };
409 $info->{'hide_payment_fields'} = [
411 my $pg = payment_gateway($cust_main, $_);
412 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
413 } @{ $info->{cust_paybys} }
416 $info->{'self_suspend_reason'} =
417 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
419 $info->{'edit_ticket_subject'} =
420 $conf->exists('ticket_system-selfservice_edit_subject') &&
421 $cust_main->edit_subject;
423 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
425 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
428 'custnum' => $custnum,
429 'access_pkgnum' => $session->{'pkgnum'},
430 'access_svcnum' => $session->{'svcnum'},
437 my($context, $session, $custnum) = _custoragent_session_custnum($p);
438 return { 'error' => $session } if $context eq 'error';
442 my $conf = new FS::Conf;
443 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
445 # if ( $FS::TicketSystem::system ) {
446 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
447 # FS::TicketSystem->init();
450 if ( $custnum ) { #customer record
452 %return = ( %return, %{ customer_info_short($p) } );
454 #redundant with customer_info_short, but we need it for several things below
455 my $search = { 'custnum' => $custnum };
456 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
457 my $cust_main = qsearchs('cust_main', $search )
458 or return { 'error' => "unknown custnum $custnum" };
460 my $list_tickets = list_tickets($p);
461 $return{'tickets'} = $list_tickets->{'tickets'};
463 if ( $session->{'pkgnum'} ) {
464 #XXX open invoices in the pkg-balances case
466 $return{'money_char'} = $conf->config("money_char") || '$';
469 invnum => $_->invnum,
470 date => time2str("%b %o, %Y", $_->_date),
472 charged => $_->charged,
474 } $cust_main->open_cust_bill;
475 $return{open_invoices} = \@open;
477 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
478 my $sth = dbh->prepare($sql) or die dbh->errstr;
479 $sth->execute($custnum) or die $sth->errstr;
480 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
481 $return{'last_invoice_date_pretty'} =
482 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
485 #customer_info_short always has nobalance on..
486 $return{small_custview} =
487 small_custview( $cust_main,
488 $return{countrydefault},
489 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
492 $return{has_ship_address} = $cust_main->has_ship_address;
493 $return{status} = $cust_main->status;
494 $return{statuscolor} = $cust_main->statuscolor;
496 # compatibility: some places in selfservice use this to determine
497 # if there's a ship address
498 if ( $return{has_ship_address} ) {
499 $return{ship_last} = $cust_main->last;
500 $return{ship_first} = $cust_main->first;
503 if (scalar($conf->config('support_packages'))) {
504 my @support_services = ();
505 foreach ($cust_main->support_services) {
506 my $seconds = $_->svc_x->seconds || 0;
507 my $time_remaining = (($seconds < 0) ? '-' : '' ).
508 int(abs($seconds)/3600)."h".
509 sprintf("%02d",(abs($seconds)%3600)/60)."m";
510 my $cust_pkg = $_->cust_pkg;
513 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
514 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
515 push @support_services, { svcnum => $_->svcnum,
516 time => $time_remaining,
521 $return{support_services} = \@support_services;
524 if ( $conf->config('prepayment_discounts-credit_type') ) {
526 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
529 } elsif ( $session->{'svcnum'} ) { #no customer record
531 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
532 or die "unknown svcnum";
533 $return{name} = $svc_acct->email;
537 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
541 return { 'error' => '',
542 'custnum' => $custnum,
548 sub customer_info_short {
551 my($context, $session, $custnum) = _custoragent_session_custnum($p);
552 return { 'error' => $session } if $context eq 'error';
556 my $conf = new FS::Conf;
558 if ( $custnum ) { #customer record
560 my $search = { 'custnum' => $custnum };
561 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
562 my $cust_main = qsearchs('cust_main', $search )
563 or return { 'error' => "unknown custnum $custnum" };
565 $return{display_custnum} = $cust_main->display_custnum;
567 if ( $session->{'pkgnum'} ) {
568 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
569 #next_bill_date from cust_pkg?
571 $return{balance} = $cust_main->balance;
572 $return{next_bill_date} = $cust_main->next_bill_date;
573 $return{next_bill_date_pretty} =
574 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
577 $return{balance_pretty} = money_pretty($return{balance});
579 $return{countrydefault} = scalar($conf->config('countrydefault'));
581 $return{small_custview} =
582 small_custview( $cust_main,
583 $return{countrydefault},
587 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
589 $return{payby} = $cust_main->payby;
591 #none of these are terribly expensive if we want 'em...
592 for (@cust_main_editable_fields) {
593 $return{$_} = $cust_main->get($_);
595 #maybe a little more expensive, but it should be cached by now
596 for (@location_editable_fields) {
597 $return{$_} = $cust_main->bill_location->get($_);
598 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
601 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
602 $return{payinfo} = $cust_main->paymask;
603 @return{'month', 'year'} = $cust_main->paydate_monthyear;
606 my @invoicing_list = $cust_main->invoicing_list;
607 $return{'invoicing_list'} =
608 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
609 $return{'postal_invoicing'} =
610 0 < ( grep { $_ eq 'POST' } @invoicing_list );
612 if ( $session->{'svcnum'} ) {
613 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
614 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
615 $return{'svcnum'} = $session->{'svcnum'};
618 } elsif ( $session->{'svcnum'} ) { #no customer record
620 #uuh, not supproted yet... die?
621 return { 'error' => 'customer_info_short not yet supported as agent' };
625 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
629 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
630 # it is not customer-specific, though it is only shown to authenticated customers
631 # it is not currently agent-specific, though at some point it might be
632 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
634 return { 'error' => '',
635 'custnum' => $custnum,
640 sub customer_recurring {
643 my($context, $session, $custnum) = _custoragent_session_custnum($p);
644 return { 'error' => $session } if $context eq 'error';
648 my $conf = new FS::Conf;
650 my $search = { 'custnum' => $custnum };
651 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
652 my $cust_main = qsearchs('cust_main', $search )
653 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
655 $return{'display_recurring'} = [ $cust_main->display_recurring ];
657 return { 'error' => '',
658 'custnum' => $custnum,
663 sub billing_history {
666 my($context, $session, $custnum) = _custoragent_session_custnum($p);
667 return { 'error' => $session } if $context eq 'error';
669 return { 'error' => 'No customer' } unless $custnum;
671 my $search = { 'custnum' => $custnum };
672 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
673 my $cust_main = qsearchs('cust_main', $search )
674 or return { 'error' => "unknown custnum $custnum" };
678 if ( $session->{'pkgnum'} ) {
679 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
680 #next_bill_date from cust_pkg?
681 return { 'error' => 'No history for package' };
684 $return{balance} = $cust_main->balance;
685 $return{balance_pretty} = money_pretty($return{balance});
686 $return{next_bill_date} = $cust_main->next_bill_date;
687 $return{next_bill_date_pretty} =
688 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
691 my $conf = new FS::Conf;
693 $return{'history'} = [
694 $cust_main->payment_history(
695 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
700 $return{'money_char'} = $conf->config("money_char") || '$',
708 my $session = _cache->get($p->{'session_id'})
709 or return { 'error' => "Can't resume session" }; #better error message
711 my $custnum = $session->{'custnum'}
712 or return { 'error' => "no customer record" };
714 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
715 or return { 'error' => "unknown custnum $custnum" };
717 my $new = new FS::cust_main { $cust_main->hash };
719 $new->set( $_ => $p->{$_} )
720 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
722 if ( exists($p->{address1}) ) {
723 my $bill_location = FS::cust_location->new({
724 map { $_ => $p->{$_} } @location_editable_fields
726 # if this is unchanged from before, cust_main::replace will ignore it
727 $new->set('bill_location' => $bill_location);
730 if ( exists($p->{ship_address1}) ) {
731 my $ship_location = FS::cust_location->new({
732 map { $_ => $p->{"ship_$_"} } @location_editable_fields
734 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
735 # Selfservice unfortunately tries to indicate "same as billing
736 # address" by sending all fields empty. Did this ever work?
737 $ship_location = $cust_main->bill_location;
739 $new->set('ship_location' => $ship_location);
741 # but if it hasn't been passed in at all, leave ship_location alone--
742 # DON'T change it to match bill_location.
745 if (exists($p->{'payby'})) {
746 $p->{'payby'} =~ /^([A-Z]{4})$/
747 or return { 'error' => "illegal_payby " . $p->{'payby'} };
751 my $conf = new FS::Conf;
753 if ( $payby =~ /^(CARD|DCRD)$/ ) {
755 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
757 if ( $new->payinfo eq $cust_main->paymask ) {
758 $new->payinfo($cust_main->payinfo);
759 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
761 $new->payinfo($p->{'payinfo'});
762 return { 'error' => 'CVV2 is required' }
763 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
764 $new->paycvv( $p->{'paycvv'} )
767 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
769 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
772 $p->{'payinfo1'} =~ /^([\dx]+)$/
773 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
775 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
776 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
778 $payinfo = $payinfo1. '@'. $payinfo2;
780 $new->payinfo( ($payinfo eq $cust_main->paymask)
781 ? $cust_main->payinfo
785 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
787 } elsif ( $payby =~ /^(BILL)$/ ) {
789 } elsif ( $payby ) { #notyet ready
790 return { 'error' => "unknown payby $payby" };
794 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
795 #false laziness with httemplate/edit/process/cust_main.cgi
796 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
797 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
799 @invoicing_list = $cust_main->invoicing_list;
802 my $error = $new->replace($cust_main, \@invoicing_list);
803 return { 'error' => $error } if $error;
806 return { 'error' => '' };
811 my $session = _cache->get($p->{'session_id'})
812 or return { 'error' => "Can't resume session" }; #better error message
818 my $conf = new FS::Conf;
819 use vars qw($payment_info); #cache for performance
820 unless ( $payment_info ) {
822 my %states = map { $_->state => 1 }
823 qsearch('cust_main_county', {
824 'country' => $conf->config('countrydefault') || 'US'
827 my %cust_paybys = map { $_ => 1 }
828 map { FS::payby->payby2payment($_) }
829 $conf->config('signup_server-payby');
831 my @cust_paybys = keys %cust_paybys;
835 #list all counties/states/countries
836 'cust_main_county' =>
837 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
839 #shortcut for one-country folks
841 [ sort { $a cmp $b } keys %states ],
843 'card_types' => card_types(),
845 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
846 'require_cvv' => $conf->exists('selfservice-require_cvv'),
847 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
849 'paytypes' => [ @FS::cust_main::paytypes ],
851 'paybys' => [ $conf->config('signup_server-payby') ],
852 'cust_paybys' => \@cust_paybys,
854 'stateid_label' => FS::Msgcat::_gettext('stateid'),
855 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
857 'show_ss' => $conf->exists('show_ss'),
858 'show_stateid' => $conf->exists('show_stateid'),
859 'show_paystate' => $conf->exists('show_bankstate'),
861 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
871 my %return = %$payment_info;
873 my $custnum = $session->{'custnum'};
875 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
876 or return { 'error' => "unknown custnum $custnum" };
878 $return{'hide_payment_fields'} = [
880 my $pg = payment_gateway($cust_main, $_);
881 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
882 } @{ $return{cust_paybys} }
885 $return{balance} = $cust_main->balance; #XXX pkg-balances?
887 $return{payname} = $cust_main->payname
888 || ( $cust_main->first. ' '. $cust_main->get('last') );
890 $return{$_} = $cust_main->bill_location->get($_)
891 for qw(address1 address2 city state zip);
893 $return{payby} = $cust_main->payby;
894 $return{stateid_state} = $cust_main->stateid_state;
896 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
897 $return{card_type} = cardtype($cust_main->payinfo);
898 $return{payinfo} = $cust_main->paymask;
900 @return{'month', 'year'} = $cust_main->paydate_monthyear;
904 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
905 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
906 $return{payinfo1} = $payinfo1;
907 $return{payinfo2} = $payinfo2;
908 $return{paytype} = $cust_main->paytype;
909 $return{paystate} = $cust_main->paystate;
910 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
913 if ( $conf->config('prepayment_discounts-credit_type') ) {
915 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
918 #doubleclick protection
920 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
921 $return{paybatch} = $return{payunique}; #back compat
923 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
925 return { 'error' => '',
931 #some false laziness with httemplate/process/payment.cgi - look there for
932 #ACH and CVV support stuff
934 sub validate_payment {
937 my $session = _cache->get($p->{'session_id'})
938 or return { 'error' => "Can't resume session" }; #better error message
940 my $custnum = $session->{'custnum'};
942 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
943 or return { 'error' => "unknown custnum $custnum" };
945 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
946 or return { 'error' => gettext('illegal_amount') };
948 return { error => 'Amount must be greater than 0' } unless $amount > 0;
950 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
951 #changing the hidden form values
952 my $conf = new FS::Conf;
953 my $fee_display = $conf->config('selfservice_process-display') || 'add';
954 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
955 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
956 if ( $fee_display eq 'add'
958 and ! $fee_skip_first || scalar($cust_main->cust_pay)
961 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
962 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
965 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
966 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
967 my $discount_term = $1;
969 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
970 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
973 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
974 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
977 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
978 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
981 $payunique = $paybatch if ! length($payunique) && length($paybatch);
983 $p->{'payby'} ||= 'CARD';
984 $p->{'payby'} =~ /^([A-Z]{4})$/
985 or return { 'error' => "illegal_payby " . $p->{'payby'} };
988 #false laziness w/process/payment.cgi
991 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
993 $p->{'payinfo1'} =~ /^([\dx]+)$/
994 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
996 $p->{'payinfo2'} =~ /^([\dx]+)$/
997 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
999 $payinfo = $payinfo1. '@'. $payinfo2;
1001 $payinfo = $cust_main->payinfo
1002 if $cust_main->paymask eq $payinfo;
1004 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1006 $payinfo = $p->{'payinfo'};
1010 #more intelligent matching will be needed here if you change
1011 #card_masking_method and don't remove existing paymasks
1012 if ( $cust_main->paymask eq $payinfo ) {
1013 $payinfo = $cust_main->payinfo;
1017 $payinfo =~ s/\D//g;
1018 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1019 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1023 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1024 return { 'error' => gettext('unknown_card_type') }
1025 if !$cust_main->tokenized($payinfo) && cardtype($payinfo) eq "Unknown";
1027 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1028 if ( cardtype($payinfo) eq 'American Express card' ) {
1029 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1030 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1033 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1034 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1037 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1038 return { 'error' => 'CVV2 is required' };
1039 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1040 return { 'error' => 'CVV2 is required' };
1044 die "unknown payby $payby";
1047 my %payby2fields = (
1048 'CARD' => [ qw( paystart_month paystart_year payissue payip
1049 address1 address2 city state zip country ) ],
1050 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1054 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1057 'cust_main' => $cust_main, #XXX or just custnum??
1058 'amount' => sprintf('%.2f', $amount),
1060 'payinfo' => $payinfo,
1061 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1062 'card_type' => $card_type,
1063 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1064 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1065 'month' => $p->{'month'},
1066 'year' => $p->{'year'},
1067 'payname' => $payname,
1068 'payunique' => $payunique,
1069 'paybatch' => $paybatch,
1070 'paycvv' => $paycvv,
1071 'payname' => $payname,
1072 'discount_term' => $discount_term,
1073 'pkgnum' => $session->{'pkgnum'},
1074 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1084 my $validate = validate_payment($p);
1085 return $validate if $validate->{'error'};
1087 my $conf = new FS::Conf;
1088 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1089 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1091 +{ map { $_=>$validate->{$_} }
1092 qw( card_type paymask payname paydate_pretty month year amount
1093 address1 address2 city state zip country
1099 sub process_stored_payment {
1102 my $session_id = $p->{'session_id'};
1104 my $payment_info = _cache->get( "payment_$session_id" )
1105 or return { 'error' => "Can't resume session" }; #better error message
1107 do_process_payment($payment_info);
1111 sub process_payment {
1114 my $payment_info = validate_payment($p);
1115 return $payment_info if $payment_info->{'error'};
1117 do_process_payment($payment_info);
1121 sub do_process_payment {
1122 my $validate = shift;
1124 my $cust_main = $validate->{'cust_main'};
1126 my $amount = delete $validate->{'amount'};
1129 my $payby = delete $validate->{'payby'};
1131 if ( $validate->{'save'} ) {
1132 my $new = new FS::cust_main { $cust_main->hash };
1133 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1134 $new->set( $_ => $validate->{$_} )
1135 foreach qw( payname paystart_month paystart_year payissue payip );
1136 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1138 my $bill_location = FS::cust_location->new({
1139 map { $_ => $validate->{$_} }
1140 qw(address1 address2 city state country zip)
1142 $new->set('bill_location' => $bill_location);
1143 # but don't allow the service address to change this way.
1145 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1146 $new->set( $_ => $validate->{$_} )
1147 foreach qw( payname payip paytype paystate
1148 stateid stateid_state );
1149 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1151 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1152 $new->set( 'paydate' => $validate->{'paydate'} );
1153 my $error = $new->replace($cust_main);
1155 #no, this causes customers to process their payments again
1156 #return { 'error' => $error };
1157 #XXX just warn verosely for now so i can figure out how these happen in
1158 # the first place, eventually should redirect them to the "change
1159 #address" page but indicate if the payment processed?
1160 delete($validate->{'payinfo'}); #don't want to log this!
1161 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1162 "NEW: ". Dumper($new)."\n".
1163 "OLD: ". Dumper($cust_main)."\n".
1164 "PACKET: ". Dumper($validate)."\n";
1170 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1174 'paynum_ref' => \$paynum,
1177 return { 'error' => $error } if $error;
1179 #no error, so order the fee package if applicable...
1180 my $conf = new FS::Conf;
1181 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1182 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1184 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1186 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1188 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1189 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1192 #and generate an invoice for it now too
1193 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1194 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1199 $cust_main->apply_payments;
1202 my $receipt_html = '';
1204 # currently supported for realtime CC only; send receipt data to SS
1205 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1208 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1211 <TD ALIGN="right">Payment#</TD>
1212 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1216 <TD ALIGN="right">Date</TD>
1218 <TD BGCOLOR="#FFFFFF"><B>! .
1219 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1225 <TD ALIGN="right">Amount</TD>
1226 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1231 <TD ALIGN="right">Payment method</TD>
1232 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1245 'amount' => sprintf('%.2f', $cust_pay->paid),
1246 'date' => $cust_pay->_date,
1247 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1248 'time_pretty' => time2str('%T', $cust_pay->_date),
1249 'auth_num' => $cust_pay->auth,
1250 'order_num' => $cust_pay->order_number,
1251 'receipt_html' => $receipt_html,
1258 'receipt_html' => '',
1265 sub realtime_collect {
1268 my $session = _cache->get($p->{'session_id'})
1269 or return { 'error' => "Can't resume session" }; #better error message
1271 my $custnum = $session->{'custnum'};
1273 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1274 or return { 'error' => "unknown custnum $custnum" };
1277 if ( $p->{'amount'} ) {
1278 $amount = $p->{'amount'};
1280 elsif ( $session->{'pkgnum'} ) {
1281 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1284 $amount = $cust_main->balance;
1287 my $error = $cust_main->realtime_collect(
1288 'method' => $p->{'method'},
1289 'amount' => $amount,
1290 'pkgnum' => $session->{'pkgnum'},
1291 'session_id' => $p->{'session_id'},
1295 return { 'error' => $error } unless ref( $error );
1297 return { 'error' => '', amount => $amount, %$error };
1300 sub start_thirdparty {
1302 my $session = _cache->get($p->{'session_id'})
1303 or return { 'error' => "Can't resume session" }; #better error message
1304 my $custnum = $session->{'custnum'};
1305 my $cust_main = FS::cust_main->by_key($custnum);
1307 my $amount = $p->{'amount'}
1308 or return { error => 'no amount' };
1310 my $result = $cust_main->create_payment(
1311 'method' => $p->{'method'},
1312 'amount' => $p->{'amount'},
1313 'pkgnum' => $session->{'pkgnum'},
1314 'session_id' => $p->{'session_id'},
1317 if ( ref($result) ) { # hashref or error
1320 return { error => $result };
1324 sub finish_thirdparty {
1326 my $session_id = delete $p->{'session_id'};
1327 my $session = _cache->get($session_id)
1328 or return { 'error' => "Can't resume session" };
1329 my $custnum = $session->{'custnum'};
1330 my $cust_main = FS::cust_main->by_key($custnum);
1332 if ( $p->{_cancel} ) {
1333 # customer backed out of making a payment
1334 return $cust_main->cancel_payment( $session_id );
1336 my $result = $cust_main->execute_payment( $session_id, %$p );
1337 if ( ref($result) ) {
1340 return { error => $result };
1344 sub process_payment_order_pkg {
1347 my $hr = process_payment($p);
1348 return $hr if $hr->{'error'};
1353 sub process_payment_order_renew {
1356 my $hr = process_payment($p);
1357 return $hr if $hr->{'error'};
1362 sub process_prepay {
1366 my $session = _cache->get($p->{'session_id'})
1367 or return { 'error' => "Can't resume session" }; #better error message
1371 my $custnum = $session->{'custnum'};
1373 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1374 or return { 'error' => "unknown custnum $custnum" };
1376 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1377 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1385 return { 'error' => $error } if $error;
1387 return { 'error' => '',
1388 'amount' => $amount,
1389 'seconds' => $seconds,
1390 'duration' => duration_exact($seconds),
1391 'upbytes' => $upbytes,
1392 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1393 'downbytes' => $downbytes,
1394 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1395 'totalbytes'=> $totalbytes,
1396 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1403 my $session = _cache->get($p->{'session_id'})
1404 or return { 'error' => "Can't resume session" }; #better error message
1406 my $custnum = $session->{'custnum'};
1408 my $invnum = $p->{'invnum'};
1410 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1411 'custnum' => $custnum } )
1412 or return { 'error' => "Can't find invnum" };
1416 return { 'error' => '',
1417 'invnum' => $invnum,
1418 'invoice_text' => join('', $cust_bill->print_text ),
1419 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1426 my $session = _cache->get($p->{'session_id'})
1427 or return { 'error' => "Can't resume session" }; #better error message
1429 my $custnum = $session->{'custnum'};
1431 my $invnum = $p->{'invnum'};
1433 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1434 'custnum' => $custnum } )
1435 or return { 'error' => "Can't find invnum" };
1439 return { 'error' => '',
1440 'invnum' => $invnum,
1441 'invoice_pdf' => $cust_bill->print_pdf({
1442 'unsquelch_cdr' => 1,
1443 'locale' => $p->{'locale'},
1449 sub legacy_invoice {
1451 my $session = _cache->get($p->{'session_id'})
1452 or return { 'error' => "Can't resume session" }; #better error message
1454 my $custnum = $session->{'custnum'};
1456 my $legacyinvnum = $p->{'legacyinvnum'};
1459 'legacyinvnum' => $legacyinvnum,
1460 'custnum' => $custnum,
1463 my $legacy_cust_bill =
1464 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1465 || qsearchs('legacy_cust_bill', \%hash )
1466 or return { 'error' => "Can't find legacyinvnum" };
1470 return { 'error' => '',
1471 'legacyinvnum' => $legacyinvnum,
1472 'legacyid' => $legacy_cust_bill->legacyid,
1473 'invoice_html' => $legacy_cust_bill->content_html,
1478 sub legacy_invoice_pdf {
1480 my $session = _cache->get($p->{'session_id'})
1481 or return { 'error' => "Can't resume session" }; #better error message
1483 my $custnum = $session->{'custnum'};
1485 my $legacyinvnum = $p->{'legacyinvnum'};
1487 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1488 'legacyinvnum' => $legacyinvnum,
1489 'custnum' => $custnum,
1490 }) or return { 'error' => "Can't find legacyinvnum" };
1494 return { 'error' => '',
1495 'legacyinvnum' => $legacyinvnum,
1496 'legacyid' => $legacy_cust_bill->legacyid,
1497 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1505 #sessioning for this? how do we get the session id to the backend invoice
1506 # template so it can add it to the link, blah
1509 if ( $p->{'invnum'} ) {
1510 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1511 or return { 'error' => 'unknown invnum' };
1512 $agentnum = $cust_bill->cust_main->agentnum;
1515 my $templatename = $p->{'template'} || $p->{'templatename'};
1517 #false laziness-ish w/view/cust_bill-logo.cgi
1519 my $conf = new FS::Conf;
1520 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1521 $templatename = "_$1";
1526 my $filename = "logo$templatename.png";
1528 return { 'error' => '',
1529 'logo' => $conf->config_binary($filename, $agentnum),
1530 'content_type' => 'image/png', #should allow gif, jpg too
1537 my $session = _cache->get($p->{'session_id'})
1538 or return { 'error' => "Can't resume session" }; #better error message
1540 my $custnum = $session->{'custnum'};
1542 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1543 or return { 'error' => "unknown custnum $custnum" };
1545 my $conf = new FS::Conf;
1547 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1549 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1554 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1555 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1556 my $owed = $_->owed;
1558 +{ 'invnum' => $_->invnum,
1559 '_date' => $_->_date,
1560 'date' => time2str("%b %o, %Y", $_->_date),
1561 'date_short' => time2str("%m-%d-%Y", $_->_date),
1562 'previous' => sprintf('%.2f', ($_->previous)[0]),
1563 'charged' => sprintf('%.2f', $_->charged),
1564 'owed' => sprintf('%.2f', $owed),
1565 'balance' => sprintf('%.2f', $balance),
1566 'lastpay' => @payments_and_credits
1567 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1573 return { 'error' => '',
1574 'balance' => $cust_main->balance,
1575 'money_char' => $conf->config("money_char") || '$',
1576 'invoices' => $invoices,
1577 'legacy_invoices' => [
1579 +{ 'legacyinvnum' => $_->legacyinvnum,
1580 'legacyid' => $_->legacyid,
1581 '_date' => $_->_date,
1582 'date' => time2str("%b %o, %Y", $_->_date),
1583 'date_short' => time2str("%m-%d-%Y", $_->_date),
1584 'charged' => sprintf('%.2f', $_->charged),
1585 'has_content' => ( length($_->content_pdf)
1586 || length($_->content_html) ),
1596 my $session = _cache->get($p->{'session_id'})
1597 or return { 'error' => "Can't resume session" }; #better error message
1599 my $custnum = $session->{'custnum'};
1601 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1602 or return { 'error' => "unknown custnum $custnum" };
1604 my @errors = $cust_main->cancel( 'quiet'=>1 );
1606 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1608 return { 'error' => $error };
1615 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1616 return { 'error' => $session } if $context eq 'error';
1618 my $search = { 'custnum' => $custnum };
1619 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1620 my $cust_main = qsearchs('cust_main', $search )
1621 or return { 'error' => "unknown custnum $custnum" };
1623 my $conf = new FS::Conf;
1624 my $immutable = $conf->exists('selfservice_immutable-package');
1626 # the duplication below is necessary:
1627 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1628 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1629 # non-backwards-compatible change breaking the software of anyone using the API
1630 # instead of the stock selfservice
1631 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1632 if( $conf->exists('selfservice_server-view-wholesale') ) {
1633 return { 'svcnum' => $session->{'svcnum'},
1634 'custnum' => $custnum,
1635 'cust_pkg' => [ map {
1637 immutable => $immutable,
1638 part_pkg => [ map $_->hashref, $_->part_pkg ],
1640 [ map $_->hashref, $_->available_part_svc ],
1642 [ map { my $ref = { $_->hash,
1643 label => [ $_->label ],
1645 $ref->{_password} = $_->svc_x->_password
1646 if $context eq 'agent'
1647 && $conf->exists('agent-showpasswords')
1648 && $_->part_svc->svcdb eq 'svc_acct';
1653 } $cust_main->cust_pkg
1656 small_custview( $cust_main, $conf->config('countrydefault') ),
1657 'wholesale_view' => 1,
1658 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1659 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1660 'lnp' => $conf->exists('svc_phone-lnp'),
1664 { 'svcnum' => $session->{'svcnum'},
1665 'custnum' => $custnum,
1666 'cust_pkg' => [ map {
1667 my $primary_cust_svc = $_->primary_cust_svc;
1670 immutable => $immutable,
1671 pkg_label => $_->pkg_locale,
1672 status => $_->status,
1673 statuscolor => $_->statuscolor,
1675 [ map { $_->hashref }
1676 grep { $_->selfservice_access ne 'hidden' }
1677 $_->available_part_svc
1680 [ map { my $ref = { $_->hash,
1681 label => [ $_->label ],
1683 $ref->{_password} = $_->svc_x->_password
1684 if $context eq 'agent'
1685 && $conf->exists('agent-showpasswords')
1686 && $_->part_svc->svcdb eq 'svc_acct';
1687 $ref->{svchash} = { $_->svc_x->hash } if
1688 $_->part_svc->svcdb eq 'svc_phone';
1689 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1690 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1693 grep { $_->part_svc->selfservice_access ne 'hidden' }
1698 ? { $primary_cust_svc->hash,
1699 label => [ $primary_cust_svc->label ],
1700 finger => $primary_cust_svc->svc_x->finger, #uuh
1701 $primary_cust_svc->part_svc->hash,
1705 } $cust_main->ncancelled_pkgs
1708 small_custview( $cust_main, $conf->config('countrydefault') ),
1709 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1717 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1718 return { 'error' => $session } if $context eq 'error';
1720 my $conf = new FS::Conf;
1722 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1723 my $search = { 'custnum' => $custnum };
1724 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1725 my $cust_main = qsearchs('cust_main', $search )
1726 or return { 'error' => "unknown custnum $custnum" };
1728 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1729 if ( ! $pkgnum && $p->{'svcnum'} ) {
1730 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1731 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1735 my @cust_pkg_usage = ();
1736 foreach my $cust_pkg ( $p->{'ncancelled'}
1737 ? $cust_main->ncancelled_pkgs
1738 : $cust_main->unsuspended_pkgs ) {
1739 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1740 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1741 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1744 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1747 foreach (@cust_pkg_usage) {
1748 my $part = $_->part_pkg_usage;
1749 my $tag = $part->description . ($part->shared ? 1 : 0);
1750 my $row = $usage_pools{$tag}
1751 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1752 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1753 $row->[2] += $part->minutes; # minutes total
1755 } # otherwise just leave them empty
1757 if ( $p->{'svcdb'} ) {
1758 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1760 : ref($p->{'svcdb'}) eq 'ARRAY'
1761 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1762 : { $p->{'svcdb'} => 1 };
1763 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1766 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1769 my @svcs; # stuff to return to the client
1770 my %bytes_used_total; # for _used columns only
1771 foreach my $cust_svc (@cust_svc) {
1772 my $svc_x = $cust_svc->svc_x;
1773 my($label, $value) = $cust_svc->label;
1774 my $part_svc = $cust_svc->part_svc;
1775 my $svcdb = $part_svc->svcdb;
1776 my $cust_pkg = $cust_svc->cust_pkg;
1777 my $part_pkg = $cust_pkg->part_pkg;
1780 'svcnum' => $cust_svc->svcnum,
1781 'display_svcnum' => $cust_svc->display_svcnum,
1785 'pkg_label' => $cust_pkg->pkg_locale,
1786 'pkg_status' => $cust_pkg->status,
1787 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1790 # would it make sense to put this in a svc_* method?
1792 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1793 my $last_bill = $cust_pkg->last_bill || 0;
1795 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
1796 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
1799 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
1800 'upbytes_used' => display_bytecount($up_used),
1801 'downbytes_used' => display_bytecount($down_used),
1802 'totalbytes_used' => display_bytecount($up_used + $down_used)
1804 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
1805 $bytes_used_total{'upbytes_used'} += $up_used;
1806 $bytes_used_total{'downbytes_used'} += $down_used;
1807 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
1810 if ( $svcdb eq 'svc_acct' ) {
1811 foreach (qw(username email finger seconds)) {
1812 $hash{$_} = $svc_x->$_;
1818 'upbytes' => display_bytecount($svc_x->upbytes),
1819 'downbytes' => display_bytecount($svc_x->downbytes),
1820 'totalbytes' => display_bytecount($svc_x->totalbytes),
1822 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1823 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1824 'recharge_upbytes' =>
1825 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1826 'recharge_downbytes' =>
1827 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1828 'recharge_totalbytes' =>
1829 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1834 } elsif ( $svcdb eq 'svc_dsl' ) {
1836 $hash{'phonenum'} = $svc_x->phonenum;
1837 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1838 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1839 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1842 $hash{'name'} = $cust_main->name;
1844 # no usage to hide here
1846 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1848 # could potentially show lots of things...
1849 $hash{'outbound'} = 1;
1850 $hash{'inbound'} = 0;
1851 if ( $svcdb eq 'svc_phone' ) {
1852 if ( $part_pkg->plan eq 'voip_inbound' ) {
1853 $hash{'outbound'} = 0;
1854 $hash{'inbound'} = 1;
1855 } elsif ( $part_pkg->option('selfservice_inbound_format')
1856 or $conf->config('selfservice-default_inbound_cdr_format')
1858 $hash{'inbound'} = 1;
1861 foreach (qw(inbound outbound)) {
1862 # hmm...we can't filter by status here, because there might
1863 # not be cdr_terminations at all. have to go by date.
1864 # find all since the last bill date.
1865 # XXX cdr types? we are going to need them.
1867 my $sum_cdr = $svc_x->sum_cdrs(
1868 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1869 'begin' => ($cust_pkg->last_bill || 0),
1871 'disable_charged_party' => 1,
1873 $hash{$_} = $sum_cdr->hashref;
1876 } # not hiding usage
1880 } # foreach $cust_svc
1882 foreach my $field (keys %bytes_used_total) {
1883 if ($field =~ /bytes/) {
1884 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
1889 'svcnum' => $session->{'svcnum'},
1890 'custnum' => $custnum,
1891 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1892 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1894 'bytes_used_total' => \%bytes_used_total,
1896 map { $usage_pools{$_} }
1900 'hide_usage' => $hide_usage,
1905 sub _customer_svc_x {
1906 my($custnum, $svcnum, $table) = (shift, shift, shift);
1907 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1909 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1910 my $search = " AND custnum = $1";
1911 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1914 'table' => ($table || 'svc_acct'),
1915 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1916 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1917 #'LEFT JOIN cust_main USING ( custnum ) ',
1918 'hashref' => $hashref,
1919 'extra_sql' => $search, #important
1924 sub svc_status_html {
1927 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1928 return { 'error' => $session } if $context eq 'error';
1930 #XXX only svc_dsl for now
1931 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1932 or return { 'error' => "Service not found" };
1934 my $html = $svc_x->getstatus_html;
1936 return { 'html' => $html };
1940 sub svc_status_hash {
1943 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1944 return { 'error' => $session } if $context eq 'error';
1946 #XXX only svc_acct for now
1947 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1948 or return { 'error' => "Service not found" };
1950 my ( $html, $hashref ) = $svc_x->export_getstatus;
1955 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1956 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1957 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1958 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1959 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1962 my( $p, $method ) = @_;
1964 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1965 return { 'error' => $session } if $context eq 'error';
1967 #XXX only svc_acct for now
1968 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1969 or return { 'error' => "Service not found" };
1971 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1973 my $error = $svc_x->$method($p); #$p? returns error?
1974 return { 'error' => $error } if $error;
1976 return {}; #? { 'error' => '' }
1980 sub acct_forward_info {
1983 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1984 return { 'error' => $session } if $context eq 'error';
1986 my $svc_forward = _customer_svc_x( $custnum,
1987 { 'srcsvc' => $p->{'svcnum'} },
1990 or return { 'error' => '',
1994 return { 'error' => '',
1995 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2000 sub process_acct_forward {
2002 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2003 return { 'error' => $session } if $context eq 'error';
2005 my $old = _customer_svc_x( $custnum,
2006 { 'srcsvc' => $p->{'svcnum'} },
2010 if ( $p->{'dst'} eq '' ) {
2012 my $error = $old->delete;
2013 return { 'error' => $error };
2015 return { 'error' => '' };
2018 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2019 'dst' => $p->{'dst'},
2024 $new->svcnum($old->svcnum);
2025 my $cust_svc = $old->cust_svc;
2026 $new->svcpart($old->svcpart);
2027 $new->pkgnuym($old->pkgnum);
2028 $error = $new->replace($old);
2030 my $conf = new FS::Conf;
2031 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2033 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2034 or return { 'error' => 'No service' }; #how would we even get here?
2036 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2038 $error = $new->insert;
2041 return { 'error' => $error };
2045 sub list_dsl_devices {
2048 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2049 return { 'error' => $session } if $context eq 'error';
2051 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2052 or return { 'error' => "Service not found" };
2055 'devices' => [ map {
2056 +{ 'mac_addr' => $_->mac_addr };
2057 } $svc_dsl->dsl_device
2063 sub add_dsl_device {
2066 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2067 return { 'error' => $session } if $context eq 'error';
2069 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2070 or return { 'error' => "Service not found" };
2072 return { 'error' => 'No MAC address supplied' }
2073 unless length($p->{'mac_addr'});
2075 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2076 'mac_addr' => scalar($p->{'mac_addr'}),
2078 my $error = $dsl_device->insert;
2079 return { 'error' => $error };
2083 sub delete_dsl_device {
2086 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2087 return { 'error' => $session } if $context eq 'error';
2089 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2090 or return { 'error' => "Service not found" };
2092 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2093 'mac_addr' => scalar($p->{'mac_addr'}),
2096 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2098 my $error = $dsl_device->delete;
2099 return { 'error' => $error };
2105 _usage_details( \&_port_graph, $p,
2106 'svcdb' => 'svc_port',
2111 my($svc_port, $begin, $end) = @_;
2113 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2114 push @usage, { 'png' => $pngOrError };
2118 sub _list_svc_usage {
2119 my($svc_acct, $begin, $end) = @_;
2121 foreach my $part_export (
2122 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2123 qw( sqlradius sqlradius_withdomain )
2125 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2130 sub list_svc_usage {
2131 _usage_details(\&_list_svc_usage, @_);
2134 sub _list_support_usage {
2135 my($svc_acct, $begin, $end) = @_;
2137 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2138 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2140 push @usage, { 'seconds' => $_->seconds,
2141 'support' => $_->support,
2142 '_date' => $_->_date,
2143 'id' => $_->transaction_id,
2144 'creator' => $_->creator,
2145 'subject' => $_->subject,
2146 'status' => $_->status,
2147 'ticketid' => $_->ticketid,
2153 sub list_support_usage {
2154 _usage_details(\&_list_support_usage, @_);
2157 sub _list_cdr_usage {
2158 # XXX CDR type support...
2159 # XXX any way to do a paged search on this?
2160 # we have to return the results all at once...
2161 my($svc_x, $begin, $end, %opt) = @_;
2162 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2166 'disable_charged_party' => 1,
2171 sub list_cdr_usage {
2173 _usage_details( \&_list_cdr_usage, $p );
2176 sub _usage_details {
2177 my($callback, $p, %opt) = @_;
2178 my $conf = FS::Conf->new;
2180 if ( $conf->exists('selfservice_hide-usage') ) {
2181 return { 'error' => 'Viewing usage is not allowed.' };
2184 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2185 return { 'error' => $session } if $context eq 'error';
2187 my $search = { 'svcnum' => $p->{'svcnum'} };
2188 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2190 my $cust_svc = qsearchs( 'cust_svc', $search );
2191 return { 'error' => 'No service selected in list_svc_usage' }
2194 my $svc_x = $cust_svc->svc_x;
2195 my $svcdb = $svc_x->table;
2196 my $cust_pkg = $cust_svc->cust_pkg;
2197 my $freq = $cust_pkg->part_pkg->freq;
2200 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2202 if ( $p->{inbound} ) {
2203 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2204 || $conf->config('selfservice-default_inbound_cdr_format')
2205 || 'source_default';
2206 $callback_opt{inbound} = 1;
2208 $format = $cust_pkg->part_pkg->option('selfservice_format')
2209 || $conf->config('selfservice-default_cdr_format')
2213 $callback_opt{format} = $format;
2214 $callback_opt{use_clid} = 1;
2215 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2218 my $start = $cust_pkg->setup;
2219 #my $end = $cust_pkg->bill; # or time?
2222 unless ( $p->{beginning} ) {
2223 $p->{beginning} = $cust_pkg->last_bill;
2224 $p->{ending} = $end;
2227 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2228 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2230 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2234 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2235 # ugly kludge, I know
2236 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2237 if (defined $delete_col) {
2238 delete($_->[$delete_col]) foreach ($header, @usage);
2242 #kinda false laziness with FS::cust_main::bill, but perhaps
2243 #we should really change this bit to DateTime and DateTime::Duration
2245 #change this bit to use Date::Manip? CAREFUL with timezones (see
2246 # mailing list archive)
2247 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2248 (localtime($p->{ending}) )[0,1,2,3,4,5];
2249 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2250 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2252 if ( $freq =~ /^\d+$/ ) {
2254 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2256 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2257 } elsif ( $freq =~ /^(\d+)w$/ ) {
2259 $nmday += $weeks * 7;
2260 $pmday -= $weeks * 7;
2261 } elsif ( $freq =~ /^(\d+)d$/ ) {
2265 } elsif ( $freq =~ /^(\d+)h$/ ) {
2270 return { 'error' => "unparsable frequency: ". $freq };
2273 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2274 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2278 'svcnum' => $p->{svcnum},
2279 'beginning' => $p->{beginning},
2280 'ending' => $p->{ending},
2281 'inbound' => $p->{inbound},
2282 'previous' => ($previous > $start) ? $previous : $start,
2283 'next' => ($next < $end) ? $next : $end,
2284 'header' => $header,
2292 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2293 return { 'error' => $session } if $context eq 'error';
2295 my $search = { 'custnum' => $custnum };
2296 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2297 my $cust_main = qsearchs('cust_main', $search )
2298 or return { 'error' => "unknown custnum $custnum" };
2300 my $status = $cust_main->status;
2302 my %order_pkg_options = ();
2303 if ( $p->{locationnum} > 0 ) {
2304 $order_pkg_options{locationnum} = delete($p->{locationnum});
2305 } elsif ( $p->{address1} ) {
2306 $order_pkg_options{'cust_location'} = new FS::cust_location {
2307 map { $_ => $p->{$_} }
2308 qw( address1 address2 city county state zip country )
2312 #false laziness w/ClientAPI/Signup.pm
2314 my $cust_pkg = new FS::cust_pkg ( {
2315 'custnum' => $custnum,
2316 'pkgpart' => $p->{'pkgpart'},
2317 'quantity' => $p->{'quantity'} || 1,
2319 my $error = $cust_pkg->check;
2320 return { 'error' => $error } if $error;
2323 unless ( $p->{'svcpart'} eq 'none' ) {
2327 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2329 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2330 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2331 $svcdb = $part_svc->svcdb;
2333 $svcdb = 'svc_acct';
2335 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2338 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2339 'svc_domain' => [ qw( domain ) ],
2340 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2341 'svc_external' => [ qw( id title ) ],
2342 'svc_pbx' => [ qw( id title ) ],
2345 my $svc_x = "FS::$svcdb"->new( {
2346 'svcpart' => $svcpart,
2347 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2350 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2353 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2354 my $acct_snarf = new FS::acct_snarf ( {
2355 'machine' => $p->{"snarf_machine$snarfnum"},
2356 'protocol' => $p->{"snarf_protocol$snarfnum"},
2357 'username' => $p->{"snarf_username$snarfnum"},
2358 '_password' => $p->{"snarf_password$snarfnum"},
2361 push @acct_snarf, $acct_snarf;
2363 $svc_x->child_objects( \@acct_snarf );
2366 my $y = $svc_x->setdefault; # arguably should be in new method
2367 return { 'error' => $y } if $y && !ref($y);
2369 $error = $svc_x->check;
2370 return { 'error' => $error } if $error;
2376 $error = $cust_main->order_pkg(
2377 'cust_pkg' => $cust_pkg,
2382 return { 'error' => $error } if $error;
2384 my $conf = new FS::Conf;
2385 if ( $conf->exists('signup_server-realtime') ) {
2387 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2390 $cust_pkg->cancel('quiet'=>1);
2393 $cust_pkg->reexport;
2397 $cust_pkg->reexport;
2400 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2402 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2409 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2410 return { 'error' => $session } if $context eq 'error';
2412 my $conf = new FS::Conf;
2413 my $immutable = $conf->exists('selfservice_immutable-package');
2414 return { 'error' => "Package modification disabled" } if $immutable;
2416 my $search = { 'custnum' => $custnum };
2417 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2418 my $cust_main = qsearchs('cust_main', $search )
2419 or return { 'error' => "unknown custnum $custnum" };
2421 my $status = $cust_main->status;
2422 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2423 or return { 'error' => "unknown package $p->{pkgnum}" };
2425 #if someone does need self-service package change of suspended packages,
2426 # figure out how to be more discriminating
2427 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2428 if $cust_pkg->status eq 'suspended';
2430 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2431 'quantity' => $p->{'quantity'} || 1,
2434 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2435 unless ref($err_or_cust_pkg);
2437 if ( $conf->exists('signup_server-realtime') ) {
2439 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2442 $err_or_cust_pkg->suspend;
2445 $err_or_cust_pkg->reexport;
2449 $err_or_cust_pkg->reexport;
2452 return { error => '', pkgnum => $cust_pkg->pkgnum };
2456 sub order_recharge {
2459 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2460 return { 'error' => $session } if $context eq 'error';
2462 my $search = { 'custnum' => $custnum };
2463 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2464 my $cust_main = qsearchs('cust_main', $search )
2465 or return { 'error' => "unknown custnum $custnum" };
2467 my $status = $cust_main->status;
2468 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2469 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2471 my $svc_x = $cust_svc->svc_x;
2472 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2475 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2476 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2477 recharge_totalbytes );
2478 my $amount = $part_pkg->option('recharge_amount', 1);
2480 my ($l, $v, $d) = $cust_svc->label; # blah
2481 my $pkg = "Recharge $v";
2483 my $bill_error = $cust_main->charge($amount, $pkg,
2484 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2485 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2486 $part_pkg->taxclass); #meh
2488 my $conf = new FS::Conf;
2489 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2491 $bill_error = _do_bop_realtime( $cust_main, $status );
2496 my $error = $svc_x->recharge (\%vhash);
2497 return { 'error' => $error } if $error;
2501 my $error = $bill_error;
2502 $error ||= $svc_x->recharge (\%vhash);
2503 return { 'error' => $error } if $error;
2506 return { error => '', svc => $cust_svc->part_svc->svc };
2510 sub _do_bop_realtime {
2511 my ($cust_main, $status, %opt) = @_;
2513 my $old_balance = $cust_main->balance;
2516 my $bill_error = $cust_main->bill(
2517 'return_bill' => \@cust_bill,
2520 $bill_error ||= $cust_main->apply_payments_and_credits;
2522 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2523 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2525 if ( $cust_main->balance > $old_balance
2526 && $cust_main->balance > 0
2527 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2528 || $status eq 'suspended'
2532 unless ( $opt{'no_invoice_void'} ) {
2534 #this used to apply a credit, but now we can void invoices...
2535 foreach my $cust_bill (@cust_bill) {
2536 my $voiderror = $cust_bill->void('automatic payment failed');
2537 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2542 return { 'error' => '_decline', 'bill_error' => $bill_error };
2545 if ( $opt{'collect'} ) {
2546 my $collect_error = $cust_main->collect();
2547 return { 'error' => '_decline', 'bill_error' => $collect_error }
2548 if $collect_error; #?
2557 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2558 return { 'error' => $session } if $context eq 'error';
2560 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2561 or return { 'error' => "unknown custnum $custnum" };
2563 my @cust_pkg = sort { $a->bill <=> $b->bill }
2564 grep { $_->part_pkg->freq ne '0' }
2565 $cust_main->ncancelled_pkgs;
2567 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2569 my $total = $cust_main->balance;
2572 my $bill = $_->bill;
2573 $total += $_->part_pkg->base_recur($_, \$bill);
2574 my $renew_date = $_->part_pkg->add_freq($_->bill);
2576 'pkgnum' => $_->pkgnum,
2577 'amount' => sprintf('%.2f', $total),
2578 'bill_date' => $_->bill,
2579 'bill_date_pretty' => time2str('%x', $_->bill),
2580 'renew_date' => $renew_date,
2581 'renew_date_pretty' => time2str('%x', $renew_date),
2582 'expire_date' => $_->expire,
2583 'expire_date_pretty' => time2str('%x', $_->expire),
2588 return { 'dates' => \@array };
2592 sub payment_info_renew_info {
2594 my $renew_info = renew_info($p);
2595 my $payment_info = payment_info($p);
2596 return { %$renew_info,
2604 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2605 return { 'error' => $session } if $context eq 'error';
2607 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2608 or return { 'error' => "unknown custnum $custnum" };
2610 my $date = $p->{'date'};
2614 #freeside-daily -n -d $date fs_daily $custnum
2615 $cust_main->bill_and_collect( 'time' => $date,
2616 'invoice_time' => $now,
2617 'actual_time' => $now,
2618 'check_freq' => '1d',
2621 return { 'error' => '' };
2627 my $session = _cache->get($p->{'session_id'})
2628 or return { 'error' => "Can't resume session" }; #better error message
2630 my $custnum = $session->{'custnum'};
2632 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2633 or return { 'error' => "unknown custnum $custnum" };
2635 my $conf = new FS::Conf;
2637 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2638 or return { 'error' => 'Permission denied' };
2640 my $pkgnum = $p->{'pkgnum'};
2642 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2643 'pkgnum' => $pkgnum, } )
2644 or return { 'error' => "unknown pkgnum $pkgnum" };
2646 my $error = $cust_pkg->suspend(reason => $reasonnum);
2647 return { 'error' => $error };
2653 my $session = _cache->get($p->{'session_id'})
2654 or return { 'error' => "Can't resume session" }; #better error message
2656 my $custnum = $session->{'custnum'};
2657 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2658 or return { 'error' => "unknown custnum $custnum" };
2660 my $pkgnum = $p->{'pkgnum'};
2661 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2662 'pkgnum' => $pkgnum, } )
2663 or return { 'error' => "unknown pkgnum $pkgnum" };
2665 my $error = $cust_pkg->cancel( 'quiet' => 1,
2666 'date' => $p->{'date'},
2668 return { 'error' => $error };
2671 sub provision_phone {
2674 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2676 #editing an existing phone number
2677 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2679 return { 'error' => $session } if $context eq 'error';
2681 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2682 return { 'error' => 'service not found' } unless $svc_phone;
2683 return { 'error' => 'invalid svcnum' }
2684 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2686 $svc_phone->email($p->{'email'})
2687 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2688 $svc_phone->forwarddst($p->{'forwarddst'})
2689 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2690 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2691 return { 'error' => $svc_phone->replace };
2695 unless ( $p->{'lnp'} ) {
2696 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2697 $p->{'lnp_status'} = "portingin";
2698 return _provision( 'FS::svc_phone',
2699 [qw(lnp_desired_due_date lnp_other_provider
2700 lnp_other_provider_account phonenum countrycode lnp_status)],
2701 [qw(phonenum countrycode)],
2707 # single DID order (the usual case)
2708 unless (scalar(@bulkdid)) {
2709 return _provision( 'FS::svc_phone',
2710 [qw(phonenum countrycode)],
2711 [qw(phonenum countrycode)],
2717 # bulk DID order case
2719 foreach my $did ( @bulkdid ) {
2720 $did =~ s/[^0-9]//g;
2721 $error = _provision( 'FS::svc_phone',
2722 [qw(phonenum countrycode)],
2723 [qw(phonenum countrycode)],
2725 'pkgnum' => $p->{'pkgnum'},
2726 'svcpart' => $p->{'svcpart'},
2728 'countrycode' => $p->{'countrycode'},
2729 'session_id' => $p->{'session_id'},
2732 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2734 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2739 warn "provision_pbx called\n"
2742 warn "provision_pbx calling _provision\n"
2744 _provision( 'FS::svc_pbx',
2745 [qw(id title max_extensions max_simultaneous ip_addr)],
2746 [qw(id title max_extensions max_simultaneous ip_addr)],
2752 sub provision_acct {
2754 warn "provision_acct called\n"
2757 return { 'error' => gettext('passwords_dont_match') }
2758 if $p->{'_password'} ne $p->{'_password2'};
2759 return { 'error' => gettext('empty_password') }
2760 unless length($p->{'_password'});
2762 if ($p->{'domsvc'}) {
2763 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2764 qw ( svcpart pkgnum ) );
2765 return { 'error' => gettext('invalid_domain') }
2766 unless ($domains{$p->{'domsvc'}});
2769 warn "provision_acct calling _provision\n"
2771 _provision( 'FS::svc_acct',
2772 [qw(username _password domsvc)],
2773 [qw(username _password domsvc)],
2779 sub provision_external {
2781 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2782 _provision( 'FS::svc_external',
2790 sub provision_forward {
2792 _provision( 'FS::svc_forward',
2793 ['srcsvc','src','dstsvc','dst'],
2800 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2801 warn "_provision called for $class\n"
2804 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2805 return { 'error' => $session } if $context eq 'error';
2807 my $search = { 'custnum' => $custnum };
2808 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2809 my $cust_main = qsearchs('cust_main', $search )
2810 or return { 'error' => "unknown custnum $custnum" };
2812 my $pkgnum = $p->{'pkgnum'};
2814 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2816 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2817 'pkgnum' => $pkgnum,
2819 or return { 'error' => "unknown pkgnum $pkgnum" };
2821 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2823 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2824 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2826 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2827 if $class ne 'FS::'. $part_svc->svcdb;
2829 warn "creating $class record\n"
2831 my $svc_x = $class->new( {
2832 'pkgnum' => $p->{'pkgnum'},
2833 'svcpart' => $p->{'svcpart'},
2834 map { $_ => $p->{$_} } @$fields
2837 my %insert_args = ();
2838 #i shouldn't be a special case here (pass an option or something)
2839 if ( $class eq 'FS::svc_phone'
2840 && grep length($p->{$_}), @location_editable_fields
2843 $insert_args{'cust_location'} = new FS::cust_location {
2844 map { $_ => $p->{$_} } @location_editable_fields
2848 warn "inserting $class record\n"
2850 my $error = $svc_x->insert(%insert_args);
2853 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2855 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2858 my $return = { 'svc' => $part_svc->svc,
2860 map { $_ => $svc_x->get($_) } @$return_fields
2862 warn "_provision returning ". Dumper($return). "\n"
2871 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2872 return { 'error' => $session } if $context eq 'error';
2874 my $search = { 'custnum' => $custnum };
2875 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2876 my $cust_main = qsearchs('cust_main', $search )
2877 or return { 'error' => "unknown custnum $custnum" };
2879 my $pkgnum = $p->{'pkgnum'};
2881 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2882 'pkgnum' => $pkgnum,
2884 or return { 'error' => "unknown pkgnum $pkgnum" };
2886 my $svcpart = $p->{'svcpart'};
2888 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2889 'svcpart' => $svcpart, } )
2890 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2891 my $part_svc = $pkg_svc->part_svc;
2893 my $conf = new FS::Conf;
2896 'svc' => $part_svc->svc,
2897 'svcdb' => $part_svc->svcdb,
2898 'pkgnum' => $pkgnum,
2899 'svcpart' => $svcpart,
2900 'custnum' => $custnum,
2902 'security_phrase' => 0, #XXX !
2903 'svc_acct_pop' => [], #XXX !
2905 'init_popstate' => '',
2910 small_custview( $cust_main, $conf->config('countrydefault') ),
2914 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2915 && $ret->{'svcdb'} eq 'svc_phone') {
2916 $ret->{'svcnum'} = $p->{'svcnum'};
2917 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2918 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2919 $ret->{'email'} = $svc_phone->email;
2920 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2924 if ($ret->{'svcdb'} eq 'svc_forward') {
2925 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2931 sub unprovision_svc {
2934 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2935 return { 'error' => $session } if $context eq 'error';
2937 my $search = { 'custnum' => $custnum };
2938 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2939 my $cust_main = qsearchs('cust_main', $search )
2940 or return { 'error' => "unknown custnum $custnum" };
2942 my $svcnum = $p->{'svcnum'};
2944 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2945 or return { 'error' => "unknown svcnum $svcnum" };
2947 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2948 unless $cust_svc->cust_pkg->custnum == $custnum;
2950 my $conf = new FS::Conf;
2952 return { 'svc' => $cust_svc->part_svc->svc,
2953 'error' => $cust_svc->cancel,
2955 small_custview( $cust_main, $conf->config('countrydefault') ),
2960 sub myaccount_passwd {
2962 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2963 return { 'error' => $session } if $context eq 'error';
2965 return { 'error' => "New passwords don't match." }
2966 if $p->{'new_password'} ne $p->{'new_password2'};
2968 return { 'error' => 'Enter new password' }
2969 unless length($p->{'new_password'});
2971 #my $search = { 'custnum' => $custnum };
2972 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2973 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2974 my $search = " AND custnum = $1";
2975 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2977 my $svc_acct = qsearchs( {
2978 'table' => 'svc_acct',
2979 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2980 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2981 'LEFT JOIN cust_main USING ( custnum ) ',
2982 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2983 'extra_sql' => $search, #important
2985 or return { 'error' => "Service not found" };
2989 my $conf = new FS::Conf;
2991 return { 'error' => 'Incorrect current password.' }
2992 if ( exists($p->{'old_password'})
2993 || $conf->exists('selfservice-password_change_oldpass')
2995 && ! $svc_acct->check_password($p->{'old_password'});
2997 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
2998 || $svc_acct->set_password($p->{'new_password'})
2999 || $svc_acct->replace();
3001 #regular pw change in self-service should change contact pw too, otherwise its
3002 #way too confusing. hell its confusing they're separate at all, but alas.
3003 #need to support the "ISP provides email that's used as a contact email" case
3005 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3006 if ( $contact && $contact->custnum == $custnum ) {
3007 #svc_acct was successful but this one returns an error? "shouldn't happen"
3008 #don't recheck is_password_allowed here; if the svc_acct password was
3009 #legal, that's good enough
3010 $error ||= $contact->change_password($p->{'new_password'});
3013 my($label, $value) = $svc_acct->cust_svc->label;
3015 return { 'error' => $error,
3025 my $info = skin_info($p);
3027 my $conf = new FS::Conf;
3028 my $verification = $conf->config('selfservice-password_reset_verification')
3029 or return { %$info, 'error' => 'Password resets disabled' };
3034 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3036 $contact = FS::contact->by_selfservice_email($p->{'email'});
3038 $cust_main = $contact->cust_main if $contact;
3040 #also look for an svc_acct, otherwise it would be super confusing
3042 my($username, $domain) = split('@', $p->{'email'});
3043 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3044 if ( $svc_domain ) {
3045 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3046 'domsvc' => $svc_domain->svcnum }
3049 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3050 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3052 #precaution: don't change svc_acct password not part of the same
3053 # customer as contact
3054 $svc_acct = '' if ! $cust_pkg
3055 || $cust_pkg->custnum != $cust_main->custnum;
3060 return { %$info, 'error' => 'Email address not found' }
3061 unless $contact || $svc_acct;
3063 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3065 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3066 or return { %$info, 'error' => 'Account not found' };
3068 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3069 'domsvc' => $svc_domain->svcnum }
3071 or return { %$info, 'error' => 'Account not found' };
3073 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3074 or return { %$info, 'error' => 'Account not found' };
3076 $cust_main = $cust_pkg->cust_main;
3081 'email' => sub { 1; },
3083 my( $p, $cust_main ) = @_;
3084 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3085 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3088 my( $p, $cust_main ) = @_;
3089 my $cust_pay = qsearchs({
3090 'table' => 'cust_pay',
3091 'hashref' => { 'custnum' => $cust_main->custnum },
3092 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3096 $p->{'amount'} == $cust_pay->paid;
3099 my( $p, $cust_main ) = @_;
3100 $p->{'zip'} eq $cust_main->zip
3101 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3105 foreach my $verify ( split(',', $verification) ) {
3107 &{ $verify{$verify} }( $p, $cust_main )
3108 or return { %$info, 'error' => 'Account not found' };
3112 #okay, we're verified
3116 my $error = $contact->send_reset_email(
3117 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3121 return { %$info, 'error' => $error }; #????
3124 } elsif ( $svc_acct ) {
3126 #create a unique session
3128 my $reset_session = {
3129 'svcnum' => $svc_acct->svcnum,
3130 'agentnum' => $svc_acct->cust_main->agentnum,
3133 my $timeout = '1 hour'; #?
3135 my $reset_session_id;
3137 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3138 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3141 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3145 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3146 $cust_main->agentnum);
3147 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3148 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3150 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3151 my $error = $msg_template->send( 'cust_main' => $cust_main,
3152 'object' => $svc_acct,
3153 'substitutions' => {
3154 'session_id' => $reset_session_id,
3158 return { %$info, 'error' => $error }; #????
3163 return { %$info, 'error' => '' };
3166 sub check_reset_passwd {
3169 my $conf = new FS::Conf;
3170 my $verification = $conf->config('selfservice-password_reset_verification')
3171 or return { 'error' => 'Password resets disabled' };
3173 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3174 or return { 'error' => "Can't resume session" }; #better error message
3176 if ( $reset_session->{'svcnum'} ) {
3178 my $svcnum = $reset_session->{'svcnum'};
3180 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3181 or return { 'error' => "Service not found" };
3183 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3184 my $info = skin_info($p);
3188 'session_id' => $p->{'session_id'},
3189 'username' => $svc_acct->username,
3192 } elsif ( $reset_session->{'contactnum'} ) {
3194 my $contactnum = $reset_session->{'contactnum'};
3196 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3197 or return { 'error' => "Contact not found" };
3199 my @contact_email = $contact->contact_email;
3200 return { 'error' => 'No contact email' } unless @contact_email;
3202 $p->{'agentnum'} = $contact->cust_main->agentnum;
3203 my $info = skin_info($p);
3207 'session_id' => $p->{'session_id'},
3208 'email' => $contact_email[0]->email, #the first?
3213 return { 'error' => 'No svcnum or contactnum in session' }; #??
3219 sub process_reset_passwd {
3222 my $conf = new FS::Conf;
3223 my $verification = $conf->config('selfservice-password_reset_verification')
3224 or return { 'error' => 'Password resets disabled' };
3226 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3227 or return { 'error' => "Can't resume session" }; #better error message
3232 if ( $reset_session->{'svcnum'} ) {
3234 my $svcnum = $reset_session->{'svcnum'};
3236 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3237 or return { 'error' => "Service not found" };
3239 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3240 $info ||= skin_info($p);
3245 if ( $reset_session->{'contactnum'} ) {
3247 my $contactnum = $reset_session->{'contactnum'};
3249 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3250 or return { 'error' => "Contact not found" };
3252 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3253 $info ||= skin_info($p);
3257 return { %$info, 'error' => "New passwords don't match." }
3258 if $p->{'new_password'} ne $p->{'new_password2'};
3260 return { %$info, 'error' => 'Enter new password' }
3261 unless length($p->{'new_password'});
3265 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3266 || $svc_acct->set_password($p->{'new_password'})
3267 || $svc_acct->replace();
3269 return { %$info, 'error' => $error } if $error;
3271 #my($label, $value) = $svc_acct->cust_svc->label;
3272 #return { 'error' => $error,
3273 # #'label' => $label,
3274 # #'value' => $value,
3281 my $error = $contact->is_password_allowed($p->{'new_password'})
3282 || $contact->change_password($p->{'new_password'});
3284 return { %$info, 'error' => $error }; # if $error;
3288 #password changed ,so remove session, don't want it reused
3289 _cache->remove($p->{'session_id'});
3291 return { %$info, 'error' => '' };
3295 sub validate_passwd {
3299 %result = ( 'fieldid' => $p->{'fieldid'} )
3300 if $p->{'fieldid'} =~ /^\w+$/;
3302 return { %result, 'password_invalid' => 'Enter new password' }
3303 unless length($p->{'check_password'});
3306 if ($p->{'svcnum'}) {
3307 # false laziness with myaccount_passwd
3308 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3309 return { %result, 'error' => $session } if $context eq 'error';
3311 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3312 my $search = " AND custnum = $1";
3313 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3315 $svc_acct = qsearchs( {
3316 'table' => 'svc_acct',
3317 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3318 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3319 'LEFT JOIN cust_main USING ( custnum ) ',
3320 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3321 'extra_sql' => $search, #important
3323 or return { %result, 'error' => "Service not found" };
3324 # end false laziness
3327 unless ($svc_acct) {
3328 my $conf = new FS::Conf;
3329 my $agentnum = $p->{'agentnum'};
3330 return { %result, 'password_valid' => 1 }
3331 if $conf->config_bool('password-insecure', $p->{'agentnum'});
3334 $svc_acct ||= new FS::svc_acct {};
3336 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3337 return { %result, 'password_invalid' => $error } if $error;
3338 return { %result, 'password_valid' => 1 };
3343 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3344 return { 'error' => $session } if $context eq 'error';
3347 if ( $session->{'pkgnum'} ) {
3349 #tickets for specific service with pkg-balances on
3350 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3351 'pkgnum' => $session->{'pkgnum'} })
3352 or return { 'error' => 'unknown package' };
3353 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3354 push @tickets, $cust_svc->tickets( $p->{status} );
3359 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3360 or return { 'error' => "unknown custnum $custnum" };
3362 @tickets = $cust_main->tickets( $p->{status} );
3365 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3366 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3367 my $conf = new FS::Conf;
3368 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3372 ($a->{'_selfservice_priority'} eq '') <=>
3373 ($b->{'_selfservice_priority'} eq '')
3376 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3382 +{ tickets => \@tickets };
3389 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3390 return { 'error' => $session } if $context eq 'error';
3392 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3393 FS::TicketSystem->init();
3395 my $conf = new FS::Conf;
3396 my $queue = $p->{'queue'}
3397 || $conf->config('ticket_system-selfservice_queueid')
3398 || $conf->config('ticket_system-default_queueid');
3400 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3401 my $err_or_ticket = FS::TicketSystem->create_ticket(
3402 '', #create RT session based on FS CurrentUser (fs_selfservice)
3404 'custnum' => $custnum,
3405 'svcnum' => $session->{'svcnum'},
3406 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3409 if ( ref($err_or_ticket) ) {
3410 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3412 return { 'error' => '',
3413 'ticket_id' => $err_or_ticket->id,
3416 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3418 return { 'error' => $err_or_ticket };
3426 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3427 return { 'error' => $session } if $context eq 'error';
3429 return { error => 'requested format not implemented' }
3430 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3432 my $conf = new FS::Conf;
3433 my $age_threshold = 0;
3434 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3435 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3437 my $search = { 'custnum' => $custnum };
3438 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3439 my $cust_main = qsearchs('cust_main', $search )
3440 or return { 'error' => "unknown custnum $custnum" };
3442 # does it make more sense to just run one sql query for this instead of all the
3443 # insanity below? would increase performance greately for large data sets?
3445 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3446 my @part_svc = $cust_pkg->part_svc;
3447 foreach my $part_svc ( @part_svc ) {
3448 if($part_svc->svcdb eq 'svc_phone'){
3449 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3450 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3451 push @svc_phone, $cust_pkg_svc->svc_x
3452 if $cust_pkg_svc->date_inserted >= $age_threshold;
3460 my($xls_r,$xls_c) = (0,0);
3463 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3464 if($p->{'format'} eq 'csv') {
3465 $csv = new Text::CSV_XS { 'always_quote' => 1,
3468 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3469 $content .= $csv->string;
3471 elsif($p->{'format'} eq 'xls') {
3472 my $XLS1 = new IO::Scalar \$content;
3473 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3474 or return { 'error' => "Error opening .xls file: $!" };
3475 $xls = $xls_workbook->add_worksheet('DIDs');
3476 foreach ( @fields ) {
3477 $xls->write(0,$xls_c++,$_);
3482 foreach my $svc_phone ( @svc_phone ) {
3483 my @cols = map { $svc_phone->$_ } @fields;
3484 if($p->{'format'} eq 'csv') {
3485 return { 'error' => 'Unable to create CSV' }
3486 unless $csv->combine(@cols);
3487 $content .= $csv->string;
3489 elsif($p->{'format'} eq 'xls') {
3492 $xls->write($xls_r,$xls_c++,$_);
3498 $xls_workbook->close() if $p->{'format'} eq 'xls';
3500 { content => $content, format => $p->{'format'}, };
3505 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3506 return { 'error' => $session } if $context eq 'error';
3508 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3509 # FS::TicketSystem->init();
3510 # return { 'error' => 'get_ticket configuration error' }
3511 # if $FS::TicketSystem::system ne 'RT_Internal';
3513 # check existence and ownership as part of this
3514 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3515 my $rt_session = FS::TicketSystem->session('');
3516 my $Ticket = FS::TicketSystem->get_ticket_object(
3518 ticket_id => $p->{'ticket_id'},
3521 return { 'error' => 'ticket not found' } if !$Ticket;
3523 if ( length( $p->{'subject'} || '' ) ) {
3525 if ( $p->{'subject'} ne $Ticket->Subject ) {
3526 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3527 return { 'error' => "unable to set subject: $msg" } if !$val;
3531 if(length($p->{'reply'})) {
3532 my @err_or_res = FS::TicketSystem->correspond_ticket(
3534 'ticket_id' => $p->{'ticket_id'},
3535 'content' => $p->{'reply'},
3538 return { 'error' => 'unable to reply to ticket' }
3539 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3542 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3543 my $err_or_ticket = FS::TicketSystem->get_ticket(
3545 'ticket_id' => $p->{'ticket_id'},
3548 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3549 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3551 return { 'error' => $err_or_ticket };
3554 my @custs = @{$err_or_ticket->{'custs'}};
3555 my @txns = @{$err_or_ticket->{'txns'}};
3558 # superseded by check in get_ticket_object
3559 #return { 'error' => 'invalid ticket requested' }
3560 #unless grep($_ eq $custnum, @custs);
3562 foreach my $txn ( @txns ) {
3563 push @filtered_txns, $txn
3564 if ($txn->{'type'} eq 'EmailRecord'
3565 || $txn->{'type'} eq 'Correspond'
3566 || $txn->{'type'} eq 'Create');
3569 warn "$me get_ticket: successful: \n"
3571 return { 'error' => '',
3572 'transactions' => \@filtered_txns,
3573 'ticket_fields' => $err_or_ticket->{'fields'},
3574 'ticket_id' => $p->{'ticket_id'},
3578 sub adjust_ticket_priority {
3580 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3581 return { 'error' => $session } if $context eq 'error';
3583 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3584 # FS::TicketSystem->init;
3585 my $ss_priority = FS::TicketSystem->selfservice_priority;
3587 return { 'error' => 'adjust_ticket_priority configuration error' }
3588 if $FS::TicketSystem::system ne 'RT_Internal'
3591 my $values = $p->{'values'}; #hashref, id => priority value
3594 foreach my $id (keys %$values) {
3595 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3596 my $Ticket = FS::TicketSystem->get_ticket_object('',
3598 'custnum' => $custnum,
3601 $ticket_error{$id} = 'ticket not found';
3605 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3606 # We're not going to implement it for RT_External.
3607 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3608 my $new_value = $values->{$id};
3609 next if $old_value eq $new_value;
3611 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3613 # AddCustomFieldValue works fine (replacing any existing value) if it's
3614 # a single-valued custom field, which it should be. If it's not, you're
3615 # doing something wrong.
3617 if ( length($new_value) ) {
3618 ($val, $msg) = $Ticket->AddCustomFieldValue(
3619 Field => $ss_priority,
3620 Value => $new_value,
3624 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3625 Field => $ss_priority,
3626 Value => $old_value,
3630 $ticket_error{$id} = $msg if !$val;
3631 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3633 return { 'error' => '',
3634 'ticket_error' => \%ticket_error,
3635 %{ customer_info($p) } # send updated customer info back
3641 sub _custoragent_session_custnum {
3644 my($context, $session, $custnum);
3645 if ( $p->{'session_id'} ) {
3647 $context = 'customer';
3648 $session = _cache->get($p->{'session_id'})
3649 or return ( 'error' => "Can't resume session" ); #better error message
3650 $custnum = $session->{'custnum'};
3652 } elsif ( $p->{'agent_session_id'} ) {
3655 my $agent_cache = new FS::ClientAPI_SessionCache( {
3656 'namespace' => 'FS::ClientAPI::Agent',
3658 $session = $agent_cache->get($p->{'agent_session_id'})
3659 or return ( 'error' => "Can't resume session" ); #better error message
3660 $custnum = $p->{'custnum'};
3664 return ( 'error' => "Can't resume session" ); #better error message
3667 ($context, $session, $custnum);