1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
53 use FS::ClientAPI::MyAccount::quotation; # just for code organization
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' && $custnum ) {
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 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
247 if ( scalar(@cust_contact) == 1 ) {
248 $session->{'custnum'} = $cust_contact[0]->custnum;
249 } elsif ( scalar(@cust_contact) ) {
250 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
254 return { error => 'No customer self-service access for contact' }; #??
259 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
261 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
262 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
264 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
265 'domsvc' => $svc_domain->svcnum, }
268 if ( $conf->exists('selfservice_server-login_svcpart') ) {
269 my @svcpart = $conf->config('selfservice_server-login_svcpart');
270 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
271 scalar( grep( $_ eq $svcpart, @svcpart ) );
276 if ( $conf->exists('selfservice_server-primary_only') ) {
279 my $cust_svc = $_->cust_svc;
280 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
281 == $cust_svc->svcpart
286 return { error => 'User not found.' } unless @svc_acct;
288 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
290 my $svc_acct = $svc_acct[0];
292 if ( $conf->exists('selfservice_server-login_svcpart') ) {
293 my @svcpart = $conf->config('selfservice_server-login_svcpart');
294 my $svcpart = $svc_acct->cust_svc->svcpart;
295 return { error => 'Invalid user.' }
296 unless grep($_ eq $svcpart, @svcpart);
299 return { error => 'Incorrect password.' }
300 unless $svc_acct->check_password($p->{'password'});
308 $session->{'svcnum'} = $svc_x->svcnum;
310 my $cust_svc = $svc_x->cust_svc;
311 my $cust_pkg = $cust_svc->cust_pkg;
313 my $cust_main = $cust_pkg->cust_main;
314 $session->{'custnum'} = $cust_main->custnum;
315 if ( $conf->exists('pkg-balances') ) {
316 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
317 $cust_main->ncancelled_pkgs;
318 $session->{'pkgnum'} = $cust_pkg->pkgnum
319 if scalar(@cust_pkg) > 1;
323 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
324 #return { error => 'Only primary user may log in.' }
325 # if $conf->exists('selfservice_server-primary_only')
326 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
327 my $part_pkg = $cust_pkg->part_pkg;
328 return { error => 'Only primary user may log in.' }
329 if $conf->exists('selfservice_server-primary_only')
330 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
336 $session_id = sha512_hex(time(). {}. rand(). $$)
337 } until ( ! defined _cache->get($session_id) ); #just in case
339 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
340 _cache->set( $session_id, $session, $timeout );
342 return { 'error' => '',
343 'session_id' => $session_id,
350 my $skin_info = skin_info($p);
351 if ( $p->{'session_id'} ) {
352 _cache->remove($p->{'session_id'});
353 return { %$skin_info, 'error' => '' };
355 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
362 my($context, $session, $custnum) = _custoragent_session_custnum($p);
363 return { 'error' => $session } if $context eq 'error';
365 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
366 or return { 'error' => "Service not found" };
368 $session->{'svcnum'} = $svc_acct->svcnum;
370 my $conf = new FS::Conf;
371 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
372 _cache->set( $p->{'session_id'}, $session, $timeout );
374 return { 'error' => '' };
380 my($context, $session, $custnum) = _custoragent_session_custnum($p);
381 return { 'error' => $session } if $context eq 'error';
383 $session->{'custnum'} = $p->{'custnum'}
384 if exists $session->{'customers'}{ $p->{'custnum'} };
386 my $conf = new FS::Conf;
387 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
388 _cache->set( $p->{'session_id'}, $session, $timeout );
390 return { 'error' => '',
391 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
395 sub payment_gateway {
397 # takes a cust_main and a cust_payby entry, returns the payment_gateway
398 my $conf = new FS::Conf;
399 my $cust_main = shift;
400 my $cust_payby = shift;
401 my $gatewaynum = $conf->config('selfservice-payment_gateway');
403 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
404 die "configured gatewaynum $gatewaynum not found!" if !$pg;
408 return '' if ! FS::payby->realtime($cust_payby);
409 my $pg = $cust_main->agent->payment_gateway(
410 'method' => FS::payby->payby2bop($cust_payby),
420 my $conf = new FS::Conf;
422 my $info = skin_info($p);
424 use vars qw( $cust_paybys ); #cache for performance
425 unless ( $cust_paybys ) {
427 my %cust_paybys = map { $_ => 1 }
428 map { FS::payby->payby2payment($_) }
429 $conf->config('signup_server-payby');
431 $cust_paybys = [ keys %cust_paybys ];
434 $info->{'cust_paybys'} = $cust_paybys;
436 my($context, $session, $custnum) = _custoragent_session_custnum($p);
437 return { 'error' => $session } if $context eq 'error';
439 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
441 $info->{'hide_payment_fields'} = [
443 my $pg = $cust_main && payment_gateway($cust_main, $_);
444 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
445 } @{ $info->{cust_paybys} }
448 $info->{'self_suspend_reason'} =
449 $conf->config('selfservice-self_suspend_reason',
450 $cust_main ? $cust_main->agentnum : ''
453 $info->{'edit_ticket_subject'} =
454 $conf->exists('ticket_system-selfservice_edit_subject') &&
455 $cust_main && $cust_main->edit_subject;
457 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
459 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
462 'custnum' => $custnum,
463 'access_pkgnum' => $session->{'pkgnum'},
464 'access_svcnum' => $session->{'svcnum'},
471 my($context, $session, $custnum) = _custoragent_session_custnum($p);
472 return { 'error' => $session } if $context eq 'error';
476 my $conf = new FS::Conf;
477 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
479 # if ( $FS::TicketSystem::system ) {
480 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
481 # FS::TicketSystem->init();
484 if ( $custnum ) { #customer record
486 %return = ( %return, %{ customer_info_short($p) } );
488 #redundant with customer_info_short, but we need it for several things below
489 my $search = { 'custnum' => $custnum };
490 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
491 my $cust_main = qsearchs('cust_main', $search )
492 or return { 'error' => "customer_info: unknown custnum $custnum" };
494 my $list_tickets = list_tickets($p);
495 $return{'tickets'} = $list_tickets->{'tickets'};
497 if ( $session->{'pkgnum'} ) {
498 #XXX open invoices in the pkg-balances case
500 $return{'money_char'} = $conf->config("money_char") || '$';
503 invnum => $_->invnum,
504 date => time2str("%b %o, %Y", $_->_date),
506 charged => $_->charged,
508 } $cust_main->open_cust_bill;
509 $return{open_invoices} = \@open;
511 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
512 my $sth = dbh->prepare($sql) or die dbh->errstr;
513 $sth->execute($custnum) or die $sth->errstr;
514 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
515 $return{'last_invoice_date_pretty'} =
516 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
519 #customer_info_short always has nobalance on..
520 $return{small_custview} =
521 small_custview( $cust_main,
522 $return{countrydefault},
523 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
526 $return{has_ship_address} = $cust_main->has_ship_address;
527 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
528 $return{statuscolor} = $cust_main->statuscolor;
529 $return{status_label} = $cust_main->status_label;
531 # compatibility: some places in selfservice use this to determine
532 # if there's a ship address
533 if ( $return{has_ship_address} ) {
534 $return{ship_last} = $cust_main->last;
535 $return{ship_first} = $cust_main->first;
538 if (scalar($conf->config('support_packages'))) {
539 my @support_services = ();
540 foreach ($cust_main->support_services) {
541 my $seconds = $_->svc_x->seconds || 0;
542 my $time_remaining = (($seconds < 0) ? '-' : '' ).
543 int(abs($seconds)/3600)."h".
544 sprintf("%02d",(abs($seconds)%3600)/60)."m";
545 my $cust_pkg = $_->cust_pkg;
548 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
549 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
550 push @support_services, { svcnum => $_->svcnum,
551 time => $time_remaining,
556 $return{support_services} = \@support_services;
559 if ( $conf->config('prepayment_discounts-credit_type') ) {
561 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
564 } elsif ( $session->{'svcnum'} ) { #no customer record
566 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
567 or die "unknown svcnum";
568 $return{name} = $svc_acct->email;
572 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
576 return { 'error' => '',
577 'custnum' => $custnum,
583 sub customer_info_short {
586 my($context, $session, $custnum) = _custoragent_session_custnum($p);
587 return { 'error' => $session } if $context eq 'error';
591 my $conf = new FS::Conf;
593 if ( $custnum ) { #customer record
595 my $search = { 'custnum' => $custnum };
596 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
597 my $cust_main = qsearchs('cust_main', $search )
598 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
600 $return{display_custnum} = $cust_main->display_custnum;
602 if ( $session->{'pkgnum'} ) {
603 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
604 #next_bill_date from cust_pkg?
606 $return{balance} = $cust_main->balance;
607 $return{next_bill_date} = $cust_main->next_bill_date;
608 $return{next_bill_date_pretty} =
609 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
612 $return{balance_pretty} = money_pretty($return{balance});
614 $return{countrydefault} = scalar($conf->config('countrydefault'));
616 $return{small_custview} =
617 small_custview( $cust_main,
618 $return{countrydefault},
622 $return{first} = $cust_main->first;
623 $return{'last'} = $cust_main->get('last');
624 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
626 $return{payby} = $cust_main->payby;
628 #none of these are terribly expensive if we want 'em...
629 for (@cust_main_editable_fields) {
630 $return{$_} = $cust_main->get($_);
632 #maybe a little more expensive, but it should be cached by now
633 for (@location_editable_fields) {
634 $return{$_} = $cust_main->bill_location->get($_)
635 if $cust_main->bill_locationnum;
636 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
637 if $cust_main->ship_locationnum;
640 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
641 $return{payinfo} = $cust_main->paymask;
642 @return{'month', 'year'} = $cust_main->paydate_monthyear;
645 my @invoicing_list = $cust_main->invoicing_list;
646 $return{'invoicing_list'} =
647 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
648 $return{'postal_invoicing'} =
649 0 < ( grep { $_ eq 'POST' } @invoicing_list );
651 if ( $session->{'svcnum'} ) {
652 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
653 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
654 $return{'svcnum'} = $session->{'svcnum'};
657 } elsif ( $session->{'svcnum'} ) { #no customer record
659 #uuh, not supproted yet... die?
660 return { 'error' => 'customer_info_short not yet supported as agent' };
664 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
668 return { 'error' => '',
669 'custnum' => $custnum,
674 sub billing_history {
677 my($context, $session, $custnum) = _custoragent_session_custnum($p);
678 return { 'error' => $session } if $context eq 'error';
680 return { 'error' => 'No customer' } unless $custnum;
682 my $search = { 'custnum' => $custnum };
683 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
684 my $cust_main = qsearchs('cust_main', $search )
685 or return { 'error' => "unknown custnum $custnum" };
689 if ( $session->{'pkgnum'} ) {
690 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
691 #next_bill_date from cust_pkg?
692 return { 'error' => 'No history for package' };
695 $return{balance} = $cust_main->balance;
696 $return{balance_pretty} = money_pretty($return{balance});
697 $return{next_bill_date} = $cust_main->next_bill_date;
698 $return{next_bill_date_pretty} =
699 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
702 my $conf = new FS::Conf;
704 $return{'history'} = [
705 $cust_main->payment_history(
706 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
711 $return{'money_char'} = $conf->config("money_char") || '$',
719 my $session = _cache->get($p->{'session_id'})
720 or return { 'error' => "Can't resume session" }; #better error message
722 my $custnum = $session->{'custnum'}
723 or return { 'error' => "no customer record" };
725 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
726 or return { 'error' => "unknown custnum $custnum" };
728 my $new = new FS::cust_main { $cust_main->hash };
730 $new->set( $_ => $p->{$_} )
731 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
733 if ( exists($p->{address1}) ) {
734 my $bill_location = FS::cust_location->new({
735 map { $_ => $p->{$_} } @location_editable_fields
737 # if this is unchanged from before, cust_main::replace will ignore it
738 $new->set('bill_location' => $bill_location);
741 if ( exists($p->{ship_address1}) ) {
742 my $ship_location = FS::cust_location->new({
743 map { $_ => $p->{"ship_$_"} } @location_editable_fields
745 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
746 # Selfservice unfortunately tries to indicate "same as billing
747 # address" by sending all fields empty. Did this ever work?
748 $ship_location = $cust_main->bill_location;
750 $new->set('ship_location' => $ship_location);
752 # but if it hasn't been passed in at all, leave ship_location alone--
753 # DON'T change it to match bill_location.
756 if (exists($p->{'payby'})) {
757 $p->{'payby'} =~ /^([A-Z]{4})$/
758 or return { 'error' => "illegal_payby " . $p->{'payby'} };
762 my $conf = new FS::Conf;
764 if ( $payby =~ /^(CARD|DCRD)$/ ) {
766 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
768 if ( $new->payinfo eq $cust_main->paymask ) {
769 $new->payinfo($cust_main->payinfo);
770 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
772 $new->payinfo($p->{'payinfo'});
773 return { 'error' => 'CVV2 is required' }
774 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
775 $new->paycvv( $p->{'paycvv'} )
778 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
780 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
783 $p->{'payinfo1'} =~ /^([\dx]+)$/
784 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
786 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
787 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
789 $payinfo = $payinfo1. '@'. $payinfo2;
791 $new->payinfo( ($payinfo eq $cust_main->paymask)
792 ? $cust_main->payinfo
796 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
798 } elsif ( $payby =~ /^(BILL)$/ ) {
800 } elsif ( $payby ) { #notyet ready
801 return { 'error' => "unknown payby $payby" };
805 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
806 #false laziness with httemplate/edit/process/cust_main.cgi
807 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
808 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
810 @invoicing_list = $cust_main->invoicing_list;
813 my $error = $new->replace($cust_main, \@invoicing_list);
814 return { 'error' => $error } if $error;
817 return { 'error' => '' };
822 my $session = _cache->get($p->{'session_id'})
823 or return { 'error' => "Can't resume session" }; #better error message
829 my $conf = new FS::Conf;
830 use vars qw($payment_info); #cache for performance
831 unless ( $payment_info ) {
833 my %states = map { $_->state => 1 }
834 qsearch('cust_main_county', {
835 'country' => $conf->config('countrydefault') || 'US'
838 my %cust_paybys = map { $_ => 1 }
839 map { FS::payby->payby2payment($_) }
840 $conf->config('signup_server-payby');
842 my @cust_paybys = keys %cust_paybys;
846 #list all counties/states/countries
847 'cust_main_county' =>
848 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
850 #shortcut for one-country folks
852 [ sort { $a cmp $b } keys %states ],
854 'card_types' => card_types(),
856 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
857 'require_cvv' => $conf->exists('selfservice-require_cvv'),
858 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
860 'paytypes' => [ FS::cust_payby::paytypes ],
862 'paybys' => [ $conf->config('signup_server-payby') ],
863 'cust_paybys' => \@cust_paybys,
865 'stateid_label' => FS::Msgcat::_gettext('stateid'),
866 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
868 'show_ss' => $conf->exists('show_ss'),
869 'show_stateid' => $conf->exists('show_stateid'),
870 'show_paystate' => $conf->exists('show_bankstate'),
872 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
874 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
883 my %return = %$payment_info;
885 my $custnum = $session->{'custnum'};
887 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
888 or return { 'error' => "unknown custnum $custnum" };
890 $return{'hide_payment_fields'} = [
892 my $pg = payment_gateway($cust_main, $_);
893 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
894 } @{ $return{cust_paybys} }
897 $return{balance} = $cust_main->balance; #XXX pkg-balances?
899 $return{payname} = $cust_main->payname
900 || ( $cust_main->first. ' '. $cust_main->get('last') );
902 $return{$_} = $cust_main->bill_location->get($_)
903 for qw(address1 address2 city state zip);
905 $return{payby} = $cust_main->payby;
906 $return{stateid_state} = $cust_main->stateid_state;
908 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
909 $return{card_type} = cardtype($cust_main->payinfo);
910 $return{payinfo} = $cust_main->paymask;
912 @return{'month', 'year'} = $cust_main->paydate_monthyear;
916 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
917 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
918 $return{payinfo1} = $payinfo1;
919 $return{payinfo2} = $payinfo2;
920 $return{paytype} = $cust_main->paytype;
921 $return{paystate} = $cust_main->paystate;
922 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
925 if ( $conf->config('prepayment_discounts-credit_type') ) {
927 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
930 #doubleclick protection
932 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
933 $return{paybatch} = $return{payunique}; #back compat
935 return { 'error' => '',
941 #some false laziness with httemplate/process/payment.cgi - look there for
942 #ACH and CVV support stuff
944 sub validate_payment {
947 my $session = _cache->get($p->{'session_id'})
948 or return { 'error' => "Can't resume session" }; #better error message
950 my $custnum = $session->{'custnum'};
952 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
953 or return { 'error' => "unknown custnum $custnum" };
955 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
956 or return { 'error' => gettext('illegal_amount') };
958 return { error => 'Amount must be greater than 0' } unless $amount > 0;
960 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
961 #changing the hidden form values
962 my $conf = new FS::Conf;
963 my $fee_display = $conf->config('selfservice_process-display') || 'add';
964 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
965 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
966 if ( $fee_display eq 'add'
968 and ! $fee_skip_first || scalar($cust_main->cust_pay)
971 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
972 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
975 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
976 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
977 my $discount_term = $1;
979 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
980 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
983 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
984 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
987 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
988 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
991 $payunique = $paybatch if ! length($payunique) && length($paybatch);
993 $p->{'payby'} ||= 'CARD';
994 $p->{'payby'} =~ /^([A-Z]{4})$/
995 or return { 'error' => "illegal_payby " . $p->{'payby'} };
998 #false laziness w/process/payment.cgi
1001 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1003 $p->{'payinfo1'} =~ /^([\dx]+)$/
1004 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1006 $p->{'payinfo2'} =~ /^([\dx]+)$/
1007 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1009 $payinfo = $payinfo1. '@'. $payinfo2;
1011 $payinfo = $cust_main->payinfo
1012 if $cust_main->paymask eq $payinfo;
1014 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1016 $payinfo = $p->{'payinfo'};
1020 #more intelligent matching will be needed here if you change
1021 #card_masking_method and don't remove existing paymasks
1022 if ( $cust_main->paymask eq $payinfo ) {
1023 $payinfo = $cust_main->payinfo;
1027 $payinfo =~ s/\D//g;
1028 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1029 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1033 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1034 return { 'error' => gettext('unknown_card_type') }
1035 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1037 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1038 if ( cardtype($payinfo) eq 'American Express card' ) {
1039 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1040 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1043 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1044 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1047 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1048 return { 'error' => 'CVV2 is required' };
1049 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1050 return { 'error' => 'CVV2 is required' };
1054 die "unknown payby $payby";
1057 my %payby2fields = (
1058 'CARD' => [ qw( paystart_month paystart_year payissue payip
1059 address1 address2 city state zip country ) ],
1060 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1064 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1067 'cust_main' => $cust_main, #XXX or just custnum??
1068 'amount' => sprintf('%.2f', $amount),
1070 'payinfo' => $payinfo,
1071 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1072 'card_type' => $card_type,
1073 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1074 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1075 'month' => $p->{'month'},
1076 'year' => $p->{'year'},
1077 'payname' => $payname,
1078 'payunique' => $payunique,
1079 'paybatch' => $paybatch,
1080 'paycvv' => $paycvv,
1081 'payname' => $payname,
1082 'discount_term' => $discount_term,
1083 'pkgnum' => $session->{'pkgnum'},
1084 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1094 my $validate = validate_payment($p);
1095 return $validate if $validate->{'error'};
1097 my $conf = new FS::Conf;
1098 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1099 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1101 +{ map { $_=>$validate->{$_} }
1102 qw( card_type paymask payname paydate_pretty month year amount
1103 address1 address2 city state zip country
1109 sub process_stored_payment {
1112 my $session_id = $p->{'session_id'};
1114 my $payment_info = _cache->get( "payment_$session_id" )
1115 or return { 'error' => "Can't resume session" }; #better error message
1117 do_process_payment($payment_info);
1121 sub process_payment {
1124 my $payment_info = validate_payment($p);
1125 return $payment_info if $payment_info->{'error'};
1127 do_process_payment($payment_info);
1131 sub do_process_payment {
1132 my $validate = shift;
1134 my $cust_main = $validate->{'cust_main'};
1136 my $amount = delete $validate->{'amount'};
1139 my $payby = delete $validate->{'payby'};
1141 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1145 'paynum_ref' => \$paynum,
1148 return { 'error' => $error } if $error;
1150 #no error, so order the fee package if applicable...
1151 my $conf = new FS::Conf;
1152 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1153 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1155 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1157 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1159 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1160 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1163 #and generate an invoice for it now too
1164 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1165 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1170 $cust_main->apply_payments;
1172 if ( $validate->{'save'} ) {
1173 my $new = new FS::cust_main { $cust_main->hash };
1174 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1175 $new->set( $_ => $validate->{$_} )
1176 foreach qw( payname paystart_month paystart_year payissue payip );
1177 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1179 my $bill_location = FS::cust_location->new({
1180 map { $_ => $validate->{$_} }
1181 qw(address1 address2 city state country zip)
1183 $new->set('bill_location' => $bill_location);
1184 # but don't allow the service address to change this way.
1186 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1187 $new->set( $_ => $validate->{$_} )
1188 foreach qw( payname payip paytype paystate
1189 stateid stateid_state );
1190 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1192 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1193 $new->set( 'paydate' => $validate->{'paydate'} );
1194 my $error = $new->replace($cust_main);
1196 #no, this causes customers to process their payments again
1197 #return { 'error' => $error };
1198 #XXX just warn verosely for now so i can figure out how these happen in
1199 # the first place, eventually should redirect them to the "change
1200 #address" page but indicate the payment did process??
1201 delete($validate->{'payinfo'}); #don't want to log this!
1202 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1203 "NEW: ". Dumper($new)."\n".
1204 "OLD: ". Dumper($cust_main)."\n".
1205 "PACKET: ". Dumper($validate)."\n";
1213 my $receipt_html = '';
1215 # currently supported for realtime CC only; send receipt data to SS
1216 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1219 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1222 <TD ALIGN="right">Payment#</TD>
1223 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1227 <TD ALIGN="right">Date</TD>
1229 <TD BGCOLOR="#FFFFFF"><B>! .
1230 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1236 <TD ALIGN="right">Amount</TD>
1237 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1242 <TD ALIGN="right">Payment method</TD>
1243 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1256 'amount' => sprintf('%.2f', $cust_pay->paid),
1257 'date' => $cust_pay->_date,
1258 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1259 'time_pretty' => time2str('%T', $cust_pay->_date),
1260 'auth_num' => $cust_pay->auth,
1261 'order_num' => $cust_pay->order_number,
1262 'receipt_html' => $receipt_html,
1269 'receipt_html' => '',
1276 sub realtime_collect {
1279 my $session = _cache->get($p->{'session_id'})
1280 or return { 'error' => "Can't resume session" }; #better error message
1282 my $custnum = $session->{'custnum'};
1284 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1285 or return { 'error' => "unknown custnum $custnum" };
1288 if ( $p->{'amount'} ) {
1289 $amount = $p->{'amount'};
1291 elsif ( $session->{'pkgnum'} ) {
1292 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1295 $amount = $cust_main->balance;
1298 my $error = $cust_main->realtime_collect(
1299 'method' => $p->{'method'},
1300 'amount' => $amount,
1301 'pkgnum' => $session->{'pkgnum'},
1302 'session_id' => $p->{'session_id'},
1306 return { 'error' => $error } unless ref( $error );
1308 return { 'error' => '', amount => $amount, %$error };
1311 sub start_thirdparty {
1313 my $session = _cache->get($p->{'session_id'})
1314 or return { 'error' => "Can't resume session" }; #better error message
1315 my $custnum = $session->{'custnum'};
1316 my $cust_main = FS::cust_main->by_key($custnum);
1318 my $amount = $p->{'amount'}
1319 or return { error => 'no amount' };
1321 my $result = $cust_main->create_payment(
1322 'method' => $p->{'method'},
1323 'amount' => $p->{'amount'},
1324 'pkgnum' => $session->{'pkgnum'},
1325 'session_id' => $p->{'session_id'},
1328 if ( ref($result) ) { # hashref or error
1331 return { error => $result };
1335 sub finish_thirdparty {
1337 my $session_id = delete $p->{'session_id'};
1338 my $session = _cache->get($session_id)
1339 or return { 'error' => "Can't resume session" };
1340 my $custnum = $session->{'custnum'};
1341 my $cust_main = FS::cust_main->by_key($custnum);
1343 if ( $p->{_cancel} ) {
1344 # customer backed out of making a payment
1345 return $cust_main->cancel_payment( $session_id );
1347 my $result = $cust_main->execute_payment( $session_id, %$p );
1348 if ( ref($result) ) {
1351 return { error => $result };
1355 sub process_payment_order_pkg {
1358 my $hr = process_payment($p);
1359 return $hr if $hr->{'error'};
1364 sub process_payment_order_renew {
1367 my $hr = process_payment($p);
1368 return $hr if $hr->{'error'};
1373 sub process_prepay {
1377 my $session = _cache->get($p->{'session_id'})
1378 or return { 'error' => "Can't resume session" }; #better error message
1382 my $custnum = $session->{'custnum'};
1384 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1385 or return { 'error' => "unknown custnum $custnum" };
1387 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1388 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1396 return { 'error' => $error } if $error;
1398 return { 'error' => '',
1399 'amount' => $amount,
1400 'seconds' => $seconds,
1401 'duration' => duration_exact($seconds),
1402 'upbytes' => $upbytes,
1403 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1404 'downbytes' => $downbytes,
1405 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1406 'totalbytes'=> $totalbytes,
1407 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1414 my $session = _cache->get($p->{'session_id'})
1415 or return { 'error' => "Can't resume session" }; #better error message
1417 my $custnum = $session->{'custnum'};
1419 my $invnum = $p->{'invnum'};
1421 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1422 'custnum' => $custnum } )
1423 or return { 'error' => "Can't find invnum" };
1427 return { 'error' => '',
1428 'invnum' => $invnum,
1429 'invoice_text' => join('', $cust_bill->print_text ),
1430 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1437 my $session = _cache->get($p->{'session_id'})
1438 or return { 'error' => "Can't resume session" }; #better error message
1440 my $custnum = $session->{'custnum'};
1442 my $invnum = $p->{'invnum'};
1444 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1445 'custnum' => $custnum } )
1446 or return { 'error' => "Can't find invnum" };
1450 return { 'error' => '',
1451 'invnum' => $invnum,
1452 'invoice_pdf' => $cust_bill->print_pdf({
1453 'unsquelch_cdr' => 1,
1454 'locale' => $p->{'locale'},
1460 sub legacy_invoice {
1462 my $session = _cache->get($p->{'session_id'})
1463 or return { 'error' => "Can't resume session" }; #better error message
1465 my $custnum = $session->{'custnum'};
1467 my $legacyinvnum = $p->{'legacyinvnum'};
1470 'legacyinvnum' => $legacyinvnum,
1471 'custnum' => $custnum,
1474 my $legacy_cust_bill =
1475 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1476 || qsearchs('legacy_cust_bill', \%hash )
1477 or return { 'error' => "Can't find legacyinvnum" };
1481 return { 'error' => '',
1482 'legacyinvnum' => $legacyinvnum,
1483 'legacyid' => $legacy_cust_bill->legacyid,
1484 'invoice_html' => $legacy_cust_bill->content_html,
1489 sub legacy_invoice_pdf {
1491 my $session = _cache->get($p->{'session_id'})
1492 or return { 'error' => "Can't resume session" }; #better error message
1494 my $custnum = $session->{'custnum'};
1496 my $legacyinvnum = $p->{'legacyinvnum'};
1498 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1499 'legacyinvnum' => $legacyinvnum,
1500 'custnum' => $custnum,
1501 }) or return { 'error' => "Can't find legacyinvnum" };
1505 return { 'error' => '',
1506 'legacyinvnum' => $legacyinvnum,
1507 'legacyid' => $legacy_cust_bill->legacyid,
1508 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1516 #sessioning for this? how do we get the session id to the backend invoice
1517 # template so it can add it to the link, blah
1520 if ( $p->{'invnum'} ) {
1521 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1522 or return { 'error' => 'unknown invnum' };
1523 $agentnum = $cust_bill->cust_main->agentnum;
1526 my $templatename = $p->{'template'} || $p->{'templatename'};
1528 #false laziness-ish w/view/cust_bill-logo.cgi
1530 my $conf = new FS::Conf;
1531 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1532 $templatename = "_$1";
1537 my $filename = "logo$templatename.png";
1539 return { 'error' => '',
1540 'logo' => $conf->config_binary($filename, $agentnum),
1541 'content_type' => 'image/png', #should allow gif, jpg too
1548 my $session = _cache->get($p->{'session_id'})
1549 or return { 'error' => "Can't resume session" }; #better error message
1551 my $custnum = $session->{'custnum'};
1553 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1554 or return { 'error' => "unknown custnum $custnum" };
1556 my $conf = new FS::Conf;
1558 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1560 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1565 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1566 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1567 my $owed = $_->owed;
1569 +{ 'invnum' => $_->invnum,
1570 '_date' => $_->_date,
1571 'date' => time2str("%b %o, %Y", $_->_date),
1572 'date_short' => time2str("%m-%d-%Y", $_->_date),
1573 'previous' => sprintf('%.2f', ($_->previous)[0]),
1574 'charged' => sprintf('%.2f', $_->charged),
1575 'owed' => sprintf('%.2f', $owed),
1576 'balance' => sprintf('%.2f', $balance),
1577 'lastpay' => @payments_and_credits
1578 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1584 return { 'error' => '',
1585 'balance' => $cust_main->balance,
1586 'money_char' => $conf->config("money_char") || '$',
1587 'invoices' => $invoices,
1588 'legacy_invoices' => [
1590 +{ 'legacyinvnum' => $_->legacyinvnum,
1591 'legacyid' => $_->legacyid,
1592 '_date' => $_->_date,
1593 'date' => time2str("%b %o, %Y", $_->_date),
1594 'date_short' => time2str("%m-%d-%Y", $_->_date),
1595 'charged' => sprintf('%.2f', $_->charged),
1596 'has_content' => ( length($_->content_pdf)
1597 || length($_->content_html) ),
1607 my $session = _cache->get($p->{'session_id'})
1608 or return { 'error' => "Can't resume session" }; #better error message
1610 my $custnum = $session->{'custnum'};
1612 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1613 or return { 'error' => "unknown custnum $custnum" };
1615 my @errors = $cust_main->cancel( 'quiet'=>1 );
1617 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1619 return { 'error' => $error };
1626 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1627 return { 'error' => $session } if $context eq 'error';
1629 my $search = { 'custnum' => $custnum };
1630 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1631 my $cust_main = qsearchs('cust_main', $search )
1632 or return { 'error' => "unknown custnum $custnum" };
1634 my $conf = new FS::Conf;
1635 my $immutable = $conf->exists('selfservice_immutable-package');
1637 # the duplication below is necessary:
1638 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1639 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1640 # non-backwards-compatible change breaking the software of anyone using the API
1641 # instead of the stock selfservice
1642 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1643 if( $conf->exists('selfservice_server-view-wholesale') ) {
1644 return { 'svcnum' => $session->{'svcnum'},
1645 'custnum' => $custnum,
1646 'cust_pkg' => [ map {
1648 immutable => $immutable,
1649 part_pkg => [ map $_->hashref, $_->part_pkg ],
1651 [ map $_->hashref, $_->available_part_svc ],
1653 [ map { my $ref = { $_->hash,
1654 label => [ $_->label ],
1656 $ref->{_password} = $_->svc_x->_password
1657 if $context eq 'agent'
1658 && $conf->exists('agent-showpasswords')
1659 && $_->part_svc->svcdb eq 'svc_acct';
1664 } $cust_main->cust_pkg
1667 small_custview( $cust_main, $conf->config('countrydefault') ),
1668 'wholesale_view' => 1,
1669 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1670 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1671 'lnp' => $conf->exists('svc_phone-lnp'),
1675 { 'svcnum' => $session->{'svcnum'},
1676 'custnum' => $custnum,
1677 'cust_pkg' => [ map {
1678 my $primary_cust_svc = $_->primary_cust_svc;
1681 immutable => $immutable,
1682 pkg_label => $_->pkg_locale,
1683 status => $_->status,
1684 statuscolor => $_->statuscolor,
1686 [ map { $_->hashref }
1687 grep { $_->selfservice_access ne 'hidden' }
1688 $_->available_part_svc
1691 [ map { my $ref = { $_->hash,
1692 label => [ $_->label ],
1694 $ref->{_password} = $_->svc_x->_password
1695 if $context eq 'agent'
1696 && $conf->exists('agent-showpasswords')
1697 && $_->part_svc->svcdb eq 'svc_acct';
1698 $ref->{svchash} = { $_->svc_x->hash } if
1699 $_->part_svc->svcdb eq 'svc_phone';
1700 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1701 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1704 grep { $_->part_svc->selfservice_access ne 'hidden' }
1709 ? { $primary_cust_svc->hash,
1710 label => [ $primary_cust_svc->label ],
1711 finger => $primary_cust_svc->svc_x->finger, #uuh
1712 $primary_cust_svc->part_svc->hash,
1716 } $cust_main->ncancelled_pkgs
1719 small_custview( $cust_main, $conf->config('countrydefault') ),
1720 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1728 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1729 return { 'error' => $session } if $context eq 'error';
1731 my $conf = new FS::Conf;
1733 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1734 my $search = { 'custnum' => $custnum };
1735 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1736 my $cust_main = qsearchs('cust_main', $search )
1737 or return { 'error' => "unknown custnum $custnum" };
1739 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1740 if ( ! $pkgnum && $p->{'svcnum'} ) {
1741 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1742 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1746 my @cust_pkg_usage = ();
1747 foreach my $cust_pkg ( $p->{'ncancelled'}
1748 ? $cust_main->ncancelled_pkgs
1749 : $cust_main->unsuspended_pkgs ) {
1750 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1751 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1752 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1755 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1758 foreach (@cust_pkg_usage) {
1759 my $part = $_->part_pkg_usage;
1760 my $tag = $part->description . ($part->shared ? 1 : 0);
1761 my $row = $usage_pools{$tag}
1762 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1763 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1764 $row->[2] += $part->minutes; # minutes total
1766 } # otherwise just leave them empty
1768 if ( $p->{'svcdb'} ) {
1769 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1771 : ref($p->{'svcdb'}) eq 'ARRAY'
1772 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1773 : { $p->{'svcdb'} => 1 };
1774 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1777 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1780 my @svcs; # stuff to return to the client
1781 foreach my $cust_svc (@cust_svc) {
1782 my $svc_x = $cust_svc->svc_x;
1783 my($label, $value) = $cust_svc->label;
1784 my $part_svc = $cust_svc->part_svc;
1785 my $svcdb = $part_svc->svcdb;
1786 my $cust_pkg = $cust_svc->cust_pkg;
1787 my $part_pkg = $cust_pkg->part_pkg;
1790 'svcnum' => $cust_svc->svcnum,
1791 'display_svcnum' => $cust_svc->display_svcnum,
1795 'pkg_label' => $cust_pkg->pkg_locale,
1796 'pkg_status' => $cust_pkg->status,
1797 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1800 # would it make sense to put this in a svc_* method?
1802 if ( $svcdb eq 'svc_acct' ) {
1803 foreach (qw(username email finger seconds)) {
1804 $hash{$_} = $svc_x->$_;
1810 'upbytes' => display_bytecount($svc_x->upbytes),
1811 'downbytes' => display_bytecount($svc_x->downbytes),
1812 'totalbytes' => display_bytecount($svc_x->totalbytes),
1814 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1815 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1816 'recharge_upbytes' =>
1817 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1818 'recharge_downbytes' =>
1819 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1820 'recharge_totalbytes' =>
1821 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1826 } elsif ( $svcdb eq 'svc_dsl' ) {
1828 $hash{'phonenum'} = $svc_x->phonenum;
1829 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1830 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1831 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1834 $hash{'name'} = $cust_main->name;
1836 # no usage to hide here
1838 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1840 # could potentially show lots of things...
1841 $hash{'outbound'} = 1;
1842 $hash{'inbound'} = 0;
1843 if ( $svcdb eq 'svc_phone' ) {
1844 if ( $part_pkg->plan eq 'voip_inbound' ) {
1845 $hash{'outbound'} = 0;
1846 $hash{'inbound'} = 1;
1847 } elsif ( $part_pkg->option('selfservice_inbound_format')
1848 or $conf->config('selfservice-default_inbound_cdr_format')
1850 $hash{'inbound'} = 1;
1853 foreach (qw(inbound outbound)) {
1854 # hmm...we can't filter by status here, because there might
1855 # not be cdr_terminations at all. have to go by date.
1856 # find all since the last bill date.
1857 # XXX cdr types? we are going to need them.
1859 my $sum_cdr = $svc_x->sum_cdrs(
1860 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1861 'begin' => ($cust_pkg->last_bill || 0),
1863 'disable_charged_party' => 1,
1865 $hash{$_} = $sum_cdr->hashref;
1868 } # not hiding usage
1872 } # foreach $cust_svc
1875 'svcnum' => $session->{'svcnum'},
1876 'custnum' => $custnum,
1877 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1878 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1881 map { $usage_pools{$_} }
1885 'hide_usage' => $hide_usage,
1890 sub _customer_svc_x {
1891 my($custnum, $svcnum, $table) = (shift, shift, shift);
1892 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1894 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1895 my $search = " AND custnum = $1";
1896 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1899 'table' => ($table || 'svc_acct'),
1900 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1901 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1902 #'LEFT JOIN cust_main USING ( custnum ) ',
1903 'hashref' => $hashref,
1904 'extra_sql' => $search, #important
1909 sub svc_status_html {
1912 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1913 return { 'error' => $session } if $context eq 'error';
1915 #XXX only svc_dsl for now
1916 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1917 or return { 'error' => "Service not found" };
1919 my $html = $svc_x->getstatus_html;
1921 return { 'html' => $html };
1925 sub svc_status_hash {
1928 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1929 return { 'error' => $session } if $context eq 'error';
1931 #XXX only svc_acct for now
1932 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1933 or return { 'error' => "Service not found" };
1935 my ( $html, $hashref ) = $svc_x->export_getstatus;
1940 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1941 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1942 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1943 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1944 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1947 my( $p, $method ) = @_;
1949 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1950 return { 'error' => $session } if $context eq 'error';
1952 #XXX only svc_acct for now
1953 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1954 or return { 'error' => "Service not found" };
1956 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1958 my $error = $svc_x->$method($p); #$p? returns error?
1959 return { 'error' => $error } if $error;
1961 return {}; #? { 'error' => '' }
1965 sub acct_forward_info {
1968 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1969 return { 'error' => $session } if $context eq 'error';
1971 my $svc_forward = _customer_svc_x( $custnum,
1972 { 'srcsvc' => $p->{'svcnum'} },
1975 or return { 'error' => '',
1979 return { 'error' => '',
1980 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1985 sub process_acct_forward {
1987 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1988 return { 'error' => $session } if $context eq 'error';
1990 my $old = _customer_svc_x( $custnum,
1991 { 'srcsvc' => $p->{'svcnum'} },
1995 if ( $p->{'dst'} eq '' ) {
1997 my $error = $old->delete;
1998 return { 'error' => $error };
2000 return { 'error' => '' };
2003 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2004 'dst' => $p->{'dst'},
2009 $new->svcnum($old->svcnum);
2010 my $cust_svc = $old->cust_svc;
2011 $new->svcpart($old->svcpart);
2012 $new->pkgnuym($old->pkgnum);
2013 $error = $new->replace($old);
2015 my $conf = new FS::Conf;
2016 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2018 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2019 or return { 'error' => 'No service' }; #how would we even get here?
2021 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2023 $error = $new->insert;
2026 return { 'error' => $error };
2030 sub list_dsl_devices {
2033 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2034 return { 'error' => $session } if $context eq 'error';
2036 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2037 or return { 'error' => "Service not found" };
2040 'devices' => [ map {
2041 +{ 'mac_addr' => $_->mac_addr };
2042 } $svc_dsl->dsl_device
2048 sub add_dsl_device {
2051 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2052 return { 'error' => $session } if $context eq 'error';
2054 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2055 or return { 'error' => "Service not found" };
2057 return { 'error' => 'No MAC address supplied' }
2058 unless length($p->{'mac_addr'});
2060 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2061 'mac_addr' => scalar($p->{'mac_addr'}),
2063 my $error = $dsl_device->insert;
2064 return { 'error' => $error };
2068 sub delete_dsl_device {
2071 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2072 return { 'error' => $session } if $context eq 'error';
2074 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2075 or return { 'error' => "Service not found" };
2077 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2078 'mac_addr' => scalar($p->{'mac_addr'}),
2081 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2083 my $error = $dsl_device->delete;
2084 return { 'error' => $error };
2090 _usage_details( \&_port_graph, $p,
2091 'svcdb' => 'svc_port',
2096 my($svc_port, $begin, $end) = @_;
2098 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2099 push @usage, { 'png' => $pngOrError };
2103 sub _list_svc_usage {
2104 my($svc_acct, $begin, $end) = @_;
2106 foreach my $part_export (
2107 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2108 qw( sqlradius sqlradius_withdomain )
2110 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2115 sub list_svc_usage {
2116 _usage_details(\&_list_svc_usage, @_);
2119 sub _list_support_usage {
2120 my($svc_acct, $begin, $end) = @_;
2122 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2123 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2125 push @usage, { 'seconds' => $_->seconds,
2126 'support' => $_->support,
2127 '_date' => $_->_date,
2128 'id' => $_->transaction_id,
2129 'creator' => $_->creator,
2130 'subject' => $_->subject,
2131 'status' => $_->status,
2132 'ticketid' => $_->ticketid,
2138 sub list_support_usage {
2139 _usage_details(\&_list_support_usage, @_);
2142 sub _list_cdr_usage {
2143 # XXX CDR type support...
2144 # XXX any way to do a paged search on this?
2145 # we have to return the results all at once...
2146 my($svc_x, $begin, $end, %opt) = @_;
2147 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2151 'disable_charged_party' => 1,
2156 sub list_cdr_usage {
2158 _usage_details( \&_list_cdr_usage, $p );
2161 sub _usage_details {
2162 my($callback, $p, %opt) = @_;
2163 my $conf = FS::Conf->new;
2165 if ( $conf->exists('selfservice_hide-usage') ) {
2166 return { 'error' => 'Viewing usage is not allowed.' };
2169 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2170 return { 'error' => $session } if $context eq 'error';
2172 my $search = { 'svcnum' => $p->{'svcnum'} };
2173 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2175 my $cust_svc = qsearchs( 'cust_svc', $search );
2176 return { 'error' => 'No service selected in list_svc_usage' }
2179 my $svc_x = $cust_svc->svc_x;
2180 my $svcdb = $svc_x->table;
2181 my $cust_pkg = $cust_svc->cust_pkg;
2182 my $freq = $cust_pkg->part_pkg->freq;
2185 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2187 if ( $p->{inbound} ) {
2188 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2189 || $conf->config('selfservice-default_inbound_cdr_format')
2190 || 'source_default';
2191 $callback_opt{inbound} = 1;
2193 $format = $cust_pkg->part_pkg->option('selfservice_format')
2194 || $conf->config('selfservice-default_cdr_format')
2198 $callback_opt{format} = $format;
2199 $callback_opt{use_clid} = 1;
2200 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2203 my $start = $cust_pkg->setup;
2204 #my $end = $cust_pkg->bill; # or time?
2207 unless ( $p->{beginning} ) {
2208 $p->{beginning} = $cust_pkg->last_bill;
2209 $p->{ending} = $end;
2212 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2213 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2215 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2219 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2220 # ugly kludge, I know
2221 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2222 if (defined $delete_col) {
2223 delete($_->[$delete_col]) foreach ($header, @usage);
2227 #kinda false laziness with FS::cust_main::bill, but perhaps
2228 #we should really change this bit to DateTime and DateTime::Duration
2230 #change this bit to use Date::Manip? CAREFUL with timezones (see
2231 # mailing list archive)
2232 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2233 (localtime($p->{ending}) )[0,1,2,3,4,5];
2234 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2235 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2237 if ( $freq =~ /^\d+$/ ) {
2239 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2241 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2242 } elsif ( $freq =~ /^(\d+)w$/ ) {
2244 $nmday += $weeks * 7;
2245 $pmday -= $weeks * 7;
2246 } elsif ( $freq =~ /^(\d+)d$/ ) {
2250 } elsif ( $freq =~ /^(\d+)h$/ ) {
2255 return { 'error' => "unparsable frequency: ". $freq };
2258 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2259 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2263 'svcnum' => $p->{svcnum},
2264 'beginning' => $p->{beginning},
2265 'ending' => $p->{ending},
2266 'inbound' => $p->{inbound},
2267 'previous' => ($previous > $start) ? $previous : $start,
2268 'next' => ($next < $end) ? $next : $end,
2269 'header' => $header,
2277 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2278 return { 'error' => $session } if $context eq 'error';
2280 my $search = { 'custnum' => $custnum };
2281 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2282 my $cust_main = qsearchs('cust_main', $search )
2283 or return { 'error' => "unknown custnum $custnum" };
2285 my $status = $cust_main->status;
2287 my %order_pkg_options = ();
2288 if ( $p->{locationnum} > 0 ) {
2289 $order_pkg_options{locationnum} = delete($p->{locationnum});
2290 } elsif ( $p->{address1} ) {
2291 $order_pkg_options{'cust_location'} = new FS::cust_location {
2292 map { $_ => $p->{$_} }
2293 qw( address1 address2 city county state zip country )
2297 #false laziness w/ClientAPI/Signup.pm
2299 my $cust_pkg = new FS::cust_pkg ( {
2300 'custnum' => $custnum,
2301 'pkgpart' => $p->{'pkgpart'},
2302 'quantity' => $p->{'quantity'} || 1,
2304 my $error = $cust_pkg->check;
2305 return { 'error' => $error } if $error;
2308 unless ( $p->{'svcpart'} eq 'none' ) {
2312 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2314 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2315 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2316 $svcdb = $part_svc->svcdb;
2318 $svcdb = 'svc_acct';
2320 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2323 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2324 'svc_domain' => [ qw( domain ) ],
2325 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2326 'svc_external' => [ qw( id title ) ],
2327 'svc_pbx' => [ qw( id title ) ],
2330 my $svc_x = "FS::$svcdb"->new( {
2331 'svcpart' => $svcpart,
2332 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2335 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2338 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2339 my $acct_snarf = new FS::acct_snarf ( {
2340 'machine' => $p->{"snarf_machine$snarfnum"},
2341 'protocol' => $p->{"snarf_protocol$snarfnum"},
2342 'username' => $p->{"snarf_username$snarfnum"},
2343 '_password' => $p->{"snarf_password$snarfnum"},
2346 push @acct_snarf, $acct_snarf;
2348 $svc_x->child_objects( \@acct_snarf );
2351 my $y = $svc_x->setdefault; # arguably should be in new method
2352 return { 'error' => $y } if $y && !ref($y);
2354 $error = $svc_x->check;
2355 return { 'error' => $error } if $error;
2361 $error = $cust_main->order_pkg(
2362 'cust_pkg' => $cust_pkg,
2367 return { 'error' => $error } if $error;
2369 my $conf = new FS::Conf;
2370 if ( $conf->exists('signup_server-realtime') ) {
2372 my $bill_error = _do_bop_realtime( $cust_main, $status );
2375 $cust_pkg->cancel('quiet'=>1);
2378 $cust_pkg->reexport;
2382 $cust_pkg->reexport;
2385 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2387 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2394 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2395 return { 'error' => $session } if $context eq 'error';
2397 my $conf = new FS::Conf;
2398 my $immutable = $conf->exists('selfservice_immutable-package');
2399 return { 'error' => "Package modification disabled" } if $immutable;
2401 my $search = { 'custnum' => $custnum };
2402 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2403 my $cust_main = qsearchs('cust_main', $search )
2404 or return { 'error' => "unknown custnum $custnum" };
2406 my $status = $cust_main->status;
2407 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2408 or return { 'error' => "unknown package $p->{pkgnum}" };
2410 #if someone does need self-service package change of suspended packages,
2411 # figure out how to be more discriminating
2412 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2413 if $cust_pkg->status eq 'suspended';
2415 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2416 'quantity' => $p->{'quantity'} || 1,
2419 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2420 unless ref($err_or_cust_pkg);
2422 if ( $conf->exists('signup_server-realtime') ) {
2424 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2427 $err_or_cust_pkg->suspend;
2430 $err_or_cust_pkg->reexport;
2434 $err_or_cust_pkg->reexport;
2437 return { error => '', pkgnum => $cust_pkg->pkgnum };
2441 sub order_recharge {
2444 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2445 return { 'error' => $session } if $context eq 'error';
2447 my $search = { 'custnum' => $custnum };
2448 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2449 my $cust_main = qsearchs('cust_main', $search )
2450 or return { 'error' => "unknown custnum $custnum" };
2452 my $status = $cust_main->status;
2453 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2454 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2456 my $svc_x = $cust_svc->svc_x;
2457 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2460 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2461 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2462 recharge_totalbytes );
2463 my $amount = $part_pkg->option('recharge_amount', 1);
2465 my ($l, $v, $d) = $cust_svc->label; # blah
2466 my $pkg = "Recharge $v";
2468 my $bill_error = $cust_main->charge($amount, $pkg,
2469 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2470 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2471 $part_pkg->taxclass); #meh
2473 my $conf = new FS::Conf;
2474 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2476 $bill_error = _do_bop_realtime( $cust_main, $status );
2481 my $error = $svc_x->recharge (\%vhash);
2482 return { 'error' => $error } if $error;
2486 my $error = $bill_error;
2487 $error ||= $svc_x->recharge (\%vhash);
2488 return { 'error' => $error } if $error;
2491 return { error => '', svc => $cust_svc->part_svc->svc };
2495 sub _do_bop_realtime {
2496 my ($cust_main, $status, %opt) = @_;
2498 my $old_balance = $cust_main->balance;
2500 my $bill_error = $cust_main->bill
2501 || $cust_main->apply_payments_and_credits;
2503 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2504 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2506 if ( $cust_main->balance > $old_balance
2507 && $cust_main->balance > 0
2508 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2509 || $status eq 'suspended'
2513 unless ( $opt{'no_credit'} ) {
2514 #this makes sense. credit is "un-doing" the invoice
2515 my $conf = new FS::Conf;
2516 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2517 'self-service decline',
2518 reason_type=>$conf->config('signup_credit_type'),
2520 $cust_main->apply_credits( 'order' => 'newest' );
2523 return { 'error' => '_decline', 'bill_error' => $bill_error };
2532 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2533 return { 'error' => $session } if $context eq 'error';
2535 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2536 or return { 'error' => "unknown custnum $custnum" };
2538 my @cust_pkg = sort { $a->bill <=> $b->bill }
2539 grep { $_->part_pkg->freq ne '0' }
2540 $cust_main->ncancelled_pkgs;
2542 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2544 my $total = $cust_main->balance;
2547 my $bill = $_->bill;
2548 $total += $_->part_pkg->base_recur($_, \$bill);
2549 my $renew_date = $_->part_pkg->add_freq($_->bill);
2551 'pkgnum' => $_->pkgnum,
2552 'amount' => sprintf('%.2f', $total),
2553 'bill_date' => $_->bill,
2554 'bill_date_pretty' => time2str('%x', $_->bill),
2555 'renew_date' => $renew_date,
2556 'renew_date_pretty' => time2str('%x', $renew_date),
2557 'expire_date' => $_->expire,
2558 'expire_date_pretty' => time2str('%x', $_->expire),
2563 return { 'dates' => \@array };
2567 sub payment_info_renew_info {
2569 my $renew_info = renew_info($p);
2570 my $payment_info = payment_info($p);
2571 return { %$renew_info,
2579 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2580 return { 'error' => $session } if $context eq 'error';
2582 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2583 or return { 'error' => "unknown custnum $custnum" };
2585 my $date = $p->{'date'};
2589 #freeside-daily -n -d $date fs_daily $custnum
2590 $cust_main->bill_and_collect( 'time' => $date,
2591 'invoice_time' => $now,
2592 'actual_time' => $now,
2593 'check_freq' => '1d',
2596 return { 'error' => '' };
2602 my $session = _cache->get($p->{'session_id'})
2603 or return { 'error' => "Can't resume session" }; #better error message
2605 my $custnum = $session->{'custnum'};
2607 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2608 or return { 'error' => "unknown custnum $custnum" };
2610 my $conf = new FS::Conf;
2612 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2613 or return { 'error' => 'Permission denied' };
2615 my $pkgnum = $p->{'pkgnum'};
2617 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2618 'pkgnum' => $pkgnum, } )
2619 or return { 'error' => "unknown pkgnum $pkgnum" };
2621 my $error = $cust_pkg->suspend(reason => $reasonnum);
2622 return { 'error' => $error };
2628 my $session = _cache->get($p->{'session_id'})
2629 or return { 'error' => "Can't resume session" }; #better error message
2631 my $custnum = $session->{'custnum'};
2633 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2634 or return { 'error' => "unknown custnum $custnum" };
2636 my $pkgnum = $p->{'pkgnum'};
2638 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2639 'pkgnum' => $pkgnum, } )
2640 or return { 'error' => "unknown pkgnum $pkgnum" };
2642 my $error = $cust_pkg->cancel('quiet' => 1);
2643 return { 'error' => $error };
2647 sub provision_phone {
2650 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2652 #editing an existing phone number
2653 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2654 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2655 return { 'error' => $session } if $context eq 'error';
2657 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2658 return { 'error' => 'service not found' } unless $svc_phone;
2659 return { 'error' => 'invalid svcnum' }
2660 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2662 $svc_phone->email($p->{'email'})
2663 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2664 $svc_phone->forwarddst($p->{'forwarddst'})
2665 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2666 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2667 return { 'error' => $svc_phone->replace };
2671 unless ( $p->{'lnp'} ) {
2672 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2673 $p->{'lnp_status'} = "portingin";
2674 return _provision( 'FS::svc_phone',
2675 [qw(lnp_desired_due_date lnp_other_provider
2676 lnp_other_provider_account phonenum countrycode lnp_status)],
2677 [qw(phonenum countrycode)],
2683 # single DID order (the usual case)
2684 unless (scalar(@bulkdid)) {
2685 return _provision( 'FS::svc_phone',
2686 [qw(phonenum countrycode)],
2687 [qw(phonenum countrycode)],
2693 # bulk DID order case
2695 foreach my $did ( @bulkdid ) {
2696 $did =~ s/[^0-9]//g;
2697 $error = _provision( 'FS::svc_phone',
2698 [qw(phonenum countrycode)],
2699 [qw(phonenum countrycode)],
2701 'pkgnum' => $p->{'pkgnum'},
2702 'svcpart' => $p->{'svcpart'},
2704 'countrycode' => $p->{'countrycode'},
2705 'session_id' => $p->{'session_id'},
2708 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2710 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2715 warn "provision_pbx called\n"
2718 warn "provision_pbx calling _provision\n"
2720 _provision( 'FS::svc_pbx',
2721 [qw(id title max_extensions max_simultaneous ip_addr)],
2722 [qw(id title max_extensions max_simultaneous ip_addr)],
2728 sub provision_acct {
2730 warn "provision_acct called\n"
2733 return { 'error' => gettext('passwords_dont_match') }
2734 if $p->{'_password'} ne $p->{'_password2'};
2735 return { 'error' => gettext('empty_password') }
2736 unless length($p->{'_password'});
2738 if ($p->{'domsvc'}) {
2739 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2740 qw ( svcpart pkgnum ) );
2741 return { 'error' => gettext('invalid_domain') }
2742 unless ($domains{$p->{'domsvc'}});
2745 warn "provision_acct calling _provision\n"
2747 _provision( 'FS::svc_acct',
2748 [qw(username _password domsvc)],
2749 [qw(username _password domsvc)],
2755 sub provision_external {
2757 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2758 _provision( 'FS::svc_external',
2766 sub provision_forward {
2768 _provision( 'FS::svc_forward',
2769 ['srcsvc','src','dstsvc','dst'],
2776 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2777 warn "_provision called for $class\n"
2780 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2781 return { 'error' => $session } if $context eq 'error';
2783 my $search = { 'custnum' => $custnum };
2784 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2785 my $cust_main = qsearchs('cust_main', $search )
2786 or return { 'error' => "unknown custnum $custnum" };
2788 my $pkgnum = $p->{'pkgnum'};
2790 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2792 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2793 'pkgnum' => $pkgnum,
2795 or return { 'error' => "unknown pkgnum $pkgnum" };
2797 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2799 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2800 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2802 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2803 if $class ne 'FS::'. $part_svc->svcdb;
2805 warn "creating $class record\n"
2807 my $svc_x = $class->new( {
2808 'pkgnum' => $p->{'pkgnum'},
2809 'svcpart' => $p->{'svcpart'},
2810 map { $_ => $p->{$_} } @$fields
2813 my %insert_args = ();
2814 #i shouldn't be a special case here (pass an option or something)
2815 if ( $class eq 'FS::svc_phone'
2816 && grep length($p->{$_}), @location_editable_fields
2819 $insert_args{'cust_location'} = new FS::cust_location {
2820 map { $_ => $p->{$_} } @location_editable_fields
2824 warn "inserting $class record\n"
2826 my $error = $svc_x->insert(%insert_args);
2829 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2831 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2834 my $return = { 'svc' => $part_svc->svc,
2836 map { $_ => $svc_x->get($_) } @$return_fields
2838 warn "_provision returning ". Dumper($return). "\n"
2847 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2848 return { 'error' => $session } if $context eq 'error';
2850 my $search = { 'custnum' => $custnum };
2851 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2852 my $cust_main = qsearchs('cust_main', $search )
2853 or return { 'error' => "unknown custnum $custnum" };
2855 my $pkgnum = $p->{'pkgnum'};
2857 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2858 'pkgnum' => $pkgnum,
2860 or return { 'error' => "unknown pkgnum $pkgnum" };
2862 my $svcpart = $p->{'svcpart'};
2864 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2865 'svcpart' => $svcpart, } )
2866 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2867 my $part_svc = $pkg_svc->part_svc;
2869 my $conf = new FS::Conf;
2872 'svc' => $part_svc->svc,
2873 'svcdb' => $part_svc->svcdb,
2874 'pkgnum' => $pkgnum,
2875 'svcpart' => $svcpart,
2876 'custnum' => $custnum,
2878 'security_phrase' => 0, #XXX !
2879 'svc_acct_pop' => [], #XXX !
2881 'init_popstate' => '',
2886 small_custview( $cust_main, $conf->config('countrydefault') ),
2890 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2891 && $ret->{'svcdb'} eq 'svc_phone') {
2892 $ret->{'svcnum'} = $p->{'svcnum'};
2893 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2894 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2895 $ret->{'email'} = $svc_phone->email;
2896 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2900 if ($ret->{'svcdb'} eq 'svc_forward') {
2901 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2907 sub unprovision_svc {
2910 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2911 return { 'error' => $session } if $context eq 'error';
2913 my $search = { 'custnum' => $custnum };
2914 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2915 my $cust_main = qsearchs('cust_main', $search )
2916 or return { 'error' => "unknown custnum $custnum" };
2918 my $svcnum = $p->{'svcnum'};
2920 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2921 or return { 'error' => "unknown svcnum $svcnum" };
2923 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2924 unless $cust_svc->cust_pkg->custnum == $custnum;
2926 my $conf = new FS::Conf;
2928 return { 'svc' => $cust_svc->part_svc->svc,
2929 'error' => $cust_svc->cancel,
2931 small_custview( $cust_main, $conf->config('countrydefault') ),
2936 sub myaccount_passwd {
2938 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2939 return { 'error' => $session } if $context eq 'error';
2941 return { 'error' => "New passwords don't match." }
2942 if $p->{'new_password'} ne $p->{'new_password2'};
2944 return { 'error' => 'Enter new password' }
2945 unless length($p->{'new_password'});
2947 #my $search = { 'custnum' => $custnum };
2948 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2949 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2950 my $search = " AND custnum = $1";
2951 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2953 my $svc_acct = qsearchs( {
2954 'table' => 'svc_acct',
2955 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2956 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2957 'LEFT JOIN cust_main USING ( custnum ) ',
2958 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2959 'extra_sql' => $search, #important
2961 or return { 'error' => "Service not found" };
2965 my $conf = new FS::Conf;
2967 return { 'error' => 'Incorrect current password.' }
2968 if ( exists($p->{'old_password'})
2969 || $conf->exists('selfservice-password_change_oldpass')
2971 && ! $svc_acct->check_password($p->{'old_password'});
2973 $error = 'Password too short.'
2974 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2975 $error = 'Password too long.'
2976 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2978 $svc_acct->set_password($p->{'new_password'});
2979 $error ||= $svc_acct->replace();
2981 #regular pw change in self-service should change contact pw too, otherwise its
2982 #way too confusing. hell its confusing they're separate at all, but alas.
2983 #need to support the "ISP provides email that's used as a contact email" case
2985 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2986 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
2987 custnum => $custnum,
2988 selfservice_access => 'Y',
2992 #svc_acct was successful but this one returns an error? "shouldn't happen"
2993 $error ||= $contact->change_password($p->{'new_password'});
2996 my($label, $value) = $svc_acct->cust_svc->label;
2998 return { 'error' => $error,
3005 # sub contact_passwd {
3007 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
3008 # return { 'error' => $session } if $context eq 'error';
3010 # return { 'error' => 'Not logged in as a contact.' }
3011 # unless $session->{'contactnum'};
3013 # return { 'error' => "New passwords don't match." }
3014 # if $p->{'new_password'} ne $p->{'new_password2'};
3016 # return { 'error' => 'Enter new password' }
3017 # unless length($p->{'new_password'});
3019 # #my $search = { 'custnum' => $custnum };
3020 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3021 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
3022 # my $search = " AND selfservice_access IS NOT NULL ".
3023 # " AND selfservice_access = 'Y' ".
3024 # " AND ( disabled IS NULL OR disabled = '' )".
3025 # " AND custnum IS NOT NULL AND custnum = $1";
3026 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3028 # my $contact = qsearchs( {
3029 # 'table' => 'contact',
3030 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
3031 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
3032 # 'extra_sql' => $search, #important
3034 # or return { 'error' => "Email not found" }; #? how did we get logged in?
3035 # # deleted since then?
3039 # # use these svc_acct length restrictions??
3040 # my $conf = new FS::Conf;
3041 # $error = 'Password too short.'
3042 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
3043 # $error = 'Password too long.'
3044 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
3046 # $error ||= $contact->change_password($p->{'new_password'});
3048 # return { 'error' => $error, };
3055 my $info = skin_info($p);
3057 my $conf = new FS::Conf;
3058 my $verification = $conf->config('selfservice-password_reset_verification')
3059 or return { %$info, 'error' => 'Password resets disabled' };
3064 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3066 $contact = FS::contact->by_selfservice_email($p->{'email'});
3069 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3070 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3073 #also look for an svc_acct, otherwise it would be super confusing
3075 my($username, $domain) = split('@', $p->{'email'});
3076 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3077 if ( $svc_domain ) {
3078 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3079 'domsvc' => $svc_domain->svcnum }
3082 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3083 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3085 #precaution: don't change svc_acct password not part of the same
3086 # customer as contact
3087 $svc_acct = '' if ! $cust_pkg
3088 || $cust_pkg->custnum != $cust_main->custnum;
3093 return { %$info, 'error' => 'Email address not found' }
3094 unless $contact || $svc_acct;
3096 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3098 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3099 or return { %$info, 'error' => 'Account not found' };
3101 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3102 'domsvc' => $svc_domain->svcnum }
3104 or return { %$info, 'error' => 'Account not found' };
3106 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3107 or return { %$info, 'error' => 'Account not found' };
3109 $cust_main = $cust_pkg->cust_main;
3113 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3114 if ! $cust_main && $verification ne 'email';
3117 'email' => sub { 1; },
3119 my( $p, $cust_main ) = @_;
3120 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3121 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3124 my( $p, $cust_main ) = @_;
3125 my $cust_pay = qsearchs({
3126 'table' => 'cust_pay',
3127 'hashref' => { 'custnum' => $cust_main->custnum },
3128 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3132 $p->{'amount'} == $cust_pay->paid;
3135 my( $p, $cust_main ) = @_;
3136 $p->{'zip'} eq $cust_main->zip
3137 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3141 foreach my $verify ( split(',', $verification) ) {
3143 &{ $verify{$verify} }( $p, $cust_main )
3144 or return { %$info, 'error' => 'Account not found' };
3148 #okay, we're verified
3152 my $error = $contact->send_reset_email(
3153 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3157 return { %$info, 'error' => $error }; #????
3160 } elsif ( $svc_acct ) {
3162 #create a unique session
3164 my $reset_session = {
3165 'svcnum' => $svc_acct->svcnum,
3169 my $timeout = '1 hour'; #?
3171 my $reset_session_id;
3173 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3174 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3177 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3181 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3182 $cust_main->agentnum);
3183 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3184 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3186 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3187 my $error = $msg_template->send( 'cust_main' => $cust_main,
3188 'object' => $svc_acct,
3189 'substitutions' => {
3190 'session_id' => $reset_session_id,
3194 return { %$info, 'error' => $error }; #????
3199 return { %$info, 'error' => '' };
3202 sub check_reset_passwd {
3205 my $conf = new FS::Conf;
3206 my $verification = $conf->config('selfservice-password_reset_verification')
3207 or return { 'error' => 'Password resets disabled' };
3209 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3210 or return { 'error' => "Can't resume session" }; #better error message
3212 if ( $reset_session->{'svcnum'} ) {
3214 my $svcnum = $reset_session->{'svcnum'};
3216 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3217 or return { 'error' => "Service not found" };
3219 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3220 my $info = skin_info($p);
3224 'session_id' => $p->{'session_id'},
3225 'username' => $svc_acct->username,
3228 } elsif ( $reset_session->{'contactnum'} ) {
3230 my $contactnum = $reset_session->{'contactnum'};
3232 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3233 or return { 'error' => "Contact not found" };
3235 my @contact_email = $contact->contact_email;
3236 return { 'error' => 'No contact email' } unless @contact_email;
3238 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3239 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3240 if scalar(@cust_contact) == 1;
3241 my $info = skin_info($p);
3245 'session_id' => $p->{'session_id'},
3246 'email' => $contact_email[0]->email, #the first?
3251 return { 'error' => 'No svcnum or contactnum in session' }; #??
3257 sub process_reset_passwd {
3260 my $conf = new FS::Conf;
3261 my $verification = $conf->config('selfservice-password_reset_verification')
3262 or return { 'error' => 'Password resets disabled' };
3264 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3265 or return { 'error' => "Can't resume session" }; #better error message
3270 if ( $reset_session->{'svcnum'} ) {
3272 my $svcnum = $reset_session->{'svcnum'};
3274 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3275 or return { 'error' => "Service not found" };
3277 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3278 $info ||= skin_info($p);
3283 if ( $reset_session->{'contactnum'} ) {
3285 my $contactnum = $reset_session->{'contactnum'};
3287 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3288 or return { 'error' => "Contact not found" };
3290 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3291 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3292 if scalar(@cust_contact) == 1;
3293 $info ||= skin_info($p);
3297 return { %$info, 'error' => "New passwords don't match." }
3298 if $p->{'new_password'} ne $p->{'new_password2'};
3300 return { %$info, 'error' => 'Enter new password' }
3301 unless length($p->{'new_password'});
3305 $svc_acct->set_password($p->{'new_password'});
3306 my $error = $svc_acct->replace();
3308 return { %$info, 'error' => $error } if $error;
3310 #my($label, $value) = $svc_acct->cust_svc->label;
3311 #return { 'error' => $error,
3312 # #'label' => $label,
3313 # #'value' => $value,
3320 my $error = $contact->change_password($p->{'new_password'});
3322 return { %$info, 'error' => $error }; # if $error;
3326 #password changed ,so remove session, don't want it reused
3327 _cache->remove($p->{'session_id'});
3329 return { %$info, 'error' => '' };
3335 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3336 return { 'error' => $session } if $context eq 'error';
3339 if ( $session->{'pkgnum'} ) {
3341 #tickets for specific service with pkg-balances on
3342 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3343 'pkgnum' => $session->{'pkgnum'} })
3344 or return { 'error' => 'unknown package' };
3345 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3346 push @tickets, $cust_svc->tickets( $p->{status} );
3351 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3352 or return { 'error' => "unknown custnum $custnum" };
3354 @tickets = $cust_main->tickets( $p->{status} );
3357 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3358 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3359 my $conf = new FS::Conf;
3360 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3364 ($a->{'_selfservice_priority'} eq '') <=>
3365 ($b->{'_selfservice_priority'} eq '')
3368 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3374 +{ tickets => \@tickets };
3381 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3382 return { 'error' => $session } if $context eq 'error';
3384 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3385 FS::TicketSystem->init();
3387 my $conf = new FS::Conf;
3388 my $queue = $p->{'queue'}
3389 || $conf->config('ticket_system-selfservice_queueid')
3390 || $conf->config('ticket_system-default_queueid');
3392 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3393 my $err_or_ticket = FS::TicketSystem->create_ticket(
3394 '', #create RT session based on FS CurrentUser (fs_selfservice)
3396 'custnum' => $custnum,
3397 'svcnum' => $session->{'svcnum'},
3398 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3401 if ( ref($err_or_ticket) ) {
3402 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3404 return { 'error' => '',
3405 'ticket_id' => $err_or_ticket->id,
3408 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3410 return { 'error' => $err_or_ticket };
3418 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3419 return { 'error' => $session } if $context eq 'error';
3421 return { error => 'requested format not implemented' }
3422 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3424 my $conf = new FS::Conf;
3425 my $age_threshold = 0;
3426 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3427 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3429 my $search = { 'custnum' => $custnum };
3430 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3431 my $cust_main = qsearchs('cust_main', $search )
3432 or return { 'error' => "unknown custnum $custnum" };
3434 # does it make more sense to just run one sql query for this instead of all the
3435 # insanity below? would increase performance greately for large data sets?
3437 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3438 my @part_svc = $cust_pkg->part_svc;
3439 foreach my $part_svc ( @part_svc ) {
3440 if($part_svc->svcdb eq 'svc_phone'){
3441 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3442 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3443 push @svc_phone, $cust_pkg_svc->svc_x
3444 if $cust_pkg_svc->date_inserted >= $age_threshold;
3452 my($xls_r,$xls_c) = (0,0);
3455 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3456 if($p->{'format'} eq 'csv') {
3457 $csv = new Text::CSV_XS { 'always_quote' => 1,
3460 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3461 $content .= $csv->string;
3463 elsif($p->{'format'} eq 'xls') {
3464 my $XLS1 = new IO::Scalar \$content;
3465 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3466 or return { 'error' => "Error opening .xls file: $!" };
3467 $xls = $xls_workbook->add_worksheet('DIDs');
3468 foreach ( @fields ) {
3469 $xls->write(0,$xls_c++,$_);
3474 foreach my $svc_phone ( @svc_phone ) {
3475 my @cols = map { $svc_phone->$_ } @fields;
3476 if($p->{'format'} eq 'csv') {
3477 return { 'error' => 'Unable to create CSV' }
3478 unless $csv->combine(@cols);
3479 $content .= $csv->string;
3481 elsif($p->{'format'} eq 'xls') {
3484 $xls->write($xls_r,$xls_c++,$_);
3490 $xls_workbook->close() if $p->{'format'} eq 'xls';
3492 { content => $content, format => $p->{'format'}, };
3497 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3498 return { 'error' => $session } if $context eq 'error';
3500 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3501 # FS::TicketSystem->init();
3502 # return { 'error' => 'get_ticket configuration error' }
3503 # if $FS::TicketSystem::system ne 'RT_Internal';
3505 # check existence and ownership as part of this
3506 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3507 my $rt_session = FS::TicketSystem->session('');
3508 my $Ticket = FS::TicketSystem->get_ticket_object(
3510 ticket_id => $p->{'ticket_id'},
3513 return { 'error' => 'ticket not found' } if !$Ticket;
3515 if ( length( $p->{'subject'} || '' ) ) {
3517 if ( $p->{'subject'} ne $Ticket->Subject ) {
3518 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3519 return { 'error' => "unable to set subject: $msg" } if !$val;
3523 if(length($p->{'reply'})) {
3524 my @err_or_res = FS::TicketSystem->correspond_ticket(
3526 'ticket_id' => $p->{'ticket_id'},
3527 'content' => $p->{'reply'},
3530 return { 'error' => 'unable to reply to ticket' }
3531 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3534 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3535 my $err_or_ticket = FS::TicketSystem->get_ticket(
3537 'ticket_id' => $p->{'ticket_id'},
3540 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3541 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3543 return { 'error' => $err_or_ticket };
3546 my @custs = @{$err_or_ticket->{'custs'}};
3547 my @txns = @{$err_or_ticket->{'txns'}};
3550 # superseded by check in get_ticket_object
3551 #return { 'error' => 'invalid ticket requested' }
3552 #unless grep($_ eq $custnum, @custs);
3554 foreach my $txn ( @txns ) {
3555 push @filtered_txns, $txn
3556 if ($txn->{'type'} eq 'EmailRecord'
3557 || $txn->{'type'} eq 'Correspond'
3558 || $txn->{'type'} eq 'Create');
3561 warn "$me get_ticket: successful: \n"
3563 return { 'error' => '',
3564 'transactions' => \@filtered_txns,
3565 'ticket_fields' => $err_or_ticket->{'fields'},
3566 'ticket_id' => $p->{'ticket_id'},
3570 sub adjust_ticket_priority {
3572 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3573 return { 'error' => $session } if $context eq 'error';
3575 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3576 # FS::TicketSystem->init;
3577 my $ss_priority = FS::TicketSystem->selfservice_priority;
3579 return { 'error' => 'adjust_ticket_priority configuration error' }
3580 if $FS::TicketSystem::system ne 'RT_Internal'
3583 my $values = $p->{'values'}; #hashref, id => priority value
3586 foreach my $id (keys %$values) {
3587 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3588 my $Ticket = FS::TicketSystem->get_ticket_object('',
3590 'custnum' => $custnum,
3593 $ticket_error{$id} = 'ticket not found';
3597 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3598 # We're not going to implement it for RT_External.
3599 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3600 my $new_value = $values->{$id};
3601 next if $old_value eq $new_value;
3603 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3605 # AddCustomFieldValue works fine (replacing any existing value) if it's
3606 # a single-valued custom field, which it should be. If it's not, you're
3607 # doing something wrong.
3609 if ( length($new_value) ) {
3610 ($val, $msg) = $Ticket->AddCustomFieldValue(
3611 Field => $ss_priority,
3612 Value => $new_value,
3616 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3617 Field => $ss_priority,
3618 Value => $old_value,
3622 $ticket_error{$id} = $msg if !$val;
3623 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3625 return { 'error' => '',
3626 'ticket_error' => \%ticket_error,
3627 %{ customer_info($p) } # send updated customer info back
3633 sub _custoragent_session_custnum {
3636 my($context, $session, $custnum);
3637 if ( $p->{'session_id'} ) {
3639 $context = 'customer';
3640 $session = _cache->get($p->{'session_id'})
3641 or return ( 'error' => "Can't resume session" ); #better error message
3642 $custnum = $session->{'custnum'};
3644 } elsif ( $p->{'agent_session_id'} ) {
3647 my $agent_cache = new FS::ClientAPI_SessionCache( {
3648 'namespace' => 'FS::ClientAPI::Agent',
3650 $session = $agent_cache->get($p->{'agent_session_id'})
3651 or return ( 'error' => "Can't resume session" ); #better error message
3652 $custnum = $p->{'custnum'};
3656 return ( 'error' => "Can't resume session" ); #better error message
3659 ($context, $session, $custnum);