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);
12 use Time::Local qw(timelocal_nocheck);
13 use Business::CreditCard;
16 use Spreadsheet::WriteExcel;
17 use FS::UI::Web::small_custview qw(small_custview); #less doh
19 use FS::UI::bytecount qw( display_bytecount );
22 use FS::Record qw(qsearch qsearchs dbh);
23 use FS::Msgcat qw(gettext);
24 use FS::Misc qw(card_types);
25 use FS::Misc::DateTime qw(parse_datetime);
27 use FS::ClientAPI_SessionCache;
39 use FS::legacy_cust_bill;
40 use FS::cust_main_county;
44 use FS::acct_rt_transaction;
48 $me = '[FS::ClientAPI::MyAccount]';
50 use vars qw( @cust_main_editable_fields @location_editable_fields );
51 @cust_main_editable_fields = qw(
52 first last daytime night fax mobile
54 payby payinfo payname paystart_month paystart_year payissue payip
55 ss paytype paystate stateid stateid_state
57 @location_editable_fields = qw(
58 address1 address2 city county state zip country
62 BEGIN { #preload to reduce time customer_info takes
63 if ( $FS::TicketSystem::system ) {
64 warn "$me: initializing ticket system\n" if $DEBUG;
65 FS::TicketSystem->init();
70 $cache ||= new FS::ClientAPI_SessionCache( {
71 'namespace' => 'FS::ClientAPI::MyAccount',
78 my($context, $session, $custnum) = _custoragent_session_custnum($p);
79 #return { 'error' => $session } if $context eq 'error';
82 if ( $context eq 'customer' ) {
84 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
87 $sth->execute($custnum) or die $sth->errstr;
89 $agentnum = $sth->fetchrow_arrayref->[0]
90 or die "no agentnum for custnum $custnum";
92 #} elsif ( $context eq 'agent' ) {
93 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
97 my $conf = new FS::Conf;
99 #false laziness w/Signup.pm
101 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
103 if ( $skin_info_cache_agent ) {
105 warn "$me loading cached skin info for agentnum $agentnum\n"
110 warn "$me populating skin info cache for agentnum $agentnum\n"
113 $skin_info_cache_agent = {
114 'agentnum' => $agentnum,
115 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
116 qw( company_name date_format ) ),
117 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
118 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
119 text_color link_color vlink_color hlink_color alink_color
120 font title_color title_align title_size menu_bgcolor menu_fontsize
123 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
124 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
126 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
127 qw( title_left_image title_right_image
128 menu_top_image menu_body_image menu_bottom_image
131 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
132 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
133 qw( head body_header body_footer company_address ) ),
136 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
140 #{ %$skin_info_cache_agent };
141 $skin_info_cache_agent;
148 my $conf = new FS::Conf;
152 'phone_login' => $conf->exists('selfservice_server-phone_login'),
153 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
154 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
155 'banner_image_md5' =>
156 md5_hex($conf->config_binary('selfservice-login_banner_image')),
163 sub login_banner_image {
165 my $conf = new FS::Conf;
166 my $image = $conf->config_binary('selfservice-login_banner_image');
168 'md5' => md5_hex($image),
173 #false laziness w/FS::ClientAPI::passwd::passwd
177 my $conf = new FS::Conf;
180 if ( $p->{'domain'} eq 'svc_phone'
181 && $conf->exists('selfservice_server-phone_login') ) {
183 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
184 return { error => 'Number not found.' } unless $svc_phone;
187 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
188 #return { error => 'Only primary user may log in.' }
189 # if $conf->exists('selfservice_server-primary_only')
190 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
192 return { error => 'Incorrect PIN.' }
193 unless $svc_phone->check_pin($p->{'password'});
199 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
200 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
202 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
203 'domsvc' => $svc_domain->svcnum, }
205 return { error => 'User not found.' } unless $svc_acct;
207 if($conf->exists('selfservice_server-login_svcpart')) {
208 my @svcpart = $conf->config('selfservice_server-login_svcpart');
209 my $svcpart = $svc_acct->cust_svc->svcpart;
210 return { error => 'Invalid user.' }
211 unless grep($_ eq $svcpart, @svcpart);
214 return { error => 'Incorrect password.' }
215 unless $svc_acct->check_password($p->{'password'});
222 'svcnum' => $svc_x->svcnum,
225 my $cust_svc = $svc_x->cust_svc;
226 my $cust_pkg = $cust_svc->cust_pkg;
228 my $cust_main = $cust_pkg->cust_main;
229 $session->{'custnum'} = $cust_main->custnum;
230 if ( $conf->exists('pkg-balances') ) {
231 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
232 $cust_main->ncancelled_pkgs;
233 $session->{'pkgnum'} = $cust_pkg->pkgnum
234 if scalar(@cust_pkg) > 1;
238 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
239 #return { error => 'Only primary user may log in.' }
240 # if $conf->exists('selfservice_server-primary_only')
241 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
242 my $part_pkg = $cust_pkg->part_pkg;
243 return { error => 'Only primary user may log in.' }
244 if $conf->exists('selfservice_server-primary_only')
245 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
249 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
250 } until ( ! defined _cache->get($session_id) ); #just in case
252 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
253 _cache->set( $session_id, $session, $timeout );
255 return { 'error' => '',
256 'session_id' => $session_id,
262 if ( $p->{'session_id'} ) {
263 _cache->remove($p->{'session_id'});
264 return { %{ skin_info($p) }, 'error' => '' };
266 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
273 my($context, $session, $custnum) = _custoragent_session_custnum($p);
274 return { 'error' => $session } if $context eq 'error';
276 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
277 or return { 'error' => "Service not found" };
279 $session->{'svcnum'} = $svc_acct->svcnum;
281 my $conf = new FS::Conf;
282 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
283 _cache->set( $p->{'session_id'}, $session, $timeout );
285 return { 'error' => '' };
289 sub payment_gateway {
291 # takes a cust_main and a cust_payby entry, returns the payment_gateway
292 my $conf = new FS::Conf;
293 my $cust_main = shift;
294 my $cust_payby = shift;
295 my $gatewaynum = $conf->config('selfservice-payment_gateway');
297 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
298 die "configured gatewaynum $gatewaynum not found!" if !$pg;
302 return '' if ! FS::payby->realtime($cust_payby);
303 my $pg = $cust_main->agent->payment_gateway(
304 'method' => FS::payby->payby2bop($cust_payby),
314 my $conf = new FS::Conf;
316 my $info = skin_info($p);
318 use vars qw( $cust_paybys ); #cache for performance
319 unless ( $cust_paybys ) {
321 my %cust_paybys = map { $_ => 1 }
322 map { FS::payby->payby2payment($_) }
323 $conf->config('signup_server-payby');
325 $cust_paybys = [ keys %cust_paybys ];
328 $info->{'cust_paybys'} = $cust_paybys;
330 my($context, $session, $custnum) = _custoragent_session_custnum($p);
331 return { 'error' => $session } if $context eq 'error';
333 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
334 or return { 'error' => "unknown custnum $custnum" };
336 $info->{'hide_payment_fields'} = [
338 my $pg = payment_gateway($cust_main, $_);
339 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
340 } @{ $info->{cust_paybys} }
343 $info->{'self_suspend_reason'} =
344 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
346 $info->{'edit_ticket_subject'} =
347 $conf->exists('ticket_system-selfservice_edit_subject') &&
348 $cust_main->edit_subject;
351 'custnum' => $custnum,
352 'access_pkgnum' => $session->{'pkgnum'},
353 'access_svcnum' => $session->{'svcnum'},
360 my($context, $session, $custnum) = _custoragent_session_custnum($p);
361 return { 'error' => $session } if $context eq 'error';
365 my $conf = new FS::Conf;
366 if ($conf->exists('cust_main-require_address2')) {
367 $return{'require_address2'} = '1';
369 $return{'require_address2'} = '';
372 if ( $FS::TicketSystem::system ) {
373 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
374 FS::TicketSystem->init();
377 if ( $custnum ) { #customer record
379 my $search = { 'custnum' => $custnum };
380 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
381 my $cust_main = qsearchs('cust_main', $search )
382 or return { 'error' => "unknown custnum $custnum" };
384 $return{display_custnum} = $cust_main->display_custnum;
386 if ( $session->{'pkgnum'} ) {
387 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
388 #next_bill_date from cust_pkg?
390 $return{balance} = $cust_main->balance;
391 $return{next_bill_date} = $cust_main->next_bill_date;
392 $return{next_bill_date_pretty} =
393 time2str('%m/%d/%Y', $return{next_bill_date} );
396 my @tickets = $cust_main->tickets;
397 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
398 if ( FS::TicketSystem->selfservice_priority ) {
399 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
403 ($a->{'_selfservice_priority'} eq '') <=>
404 ($b->{'_selfservice_priority'} eq '')
407 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
413 $return{tickets} = \@tickets;
416 unless ( $session->{'pkgnum'} ) {
419 invnum => $_->invnum,
420 date => time2str("%b %o, %Y", $_->_date),
423 } $cust_main->open_cust_bill;
424 $return{open_invoices} = \@open;
426 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
427 my $sth = dbh->prepare($sql) or die dbh->errstr;
428 $sth->execute($custnum) or die $sth->errstr;
429 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
430 $return{'last_invoice_date_pretty'} =
431 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
434 $return{countrydefault} = scalar($conf->config('countrydefault'));
436 $return{small_custview} =
437 small_custview( $cust_main,
438 $return{countrydefault},
439 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
442 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
444 $return{has_ship_address} = $cust_main->has_ship_address;
445 $return{status} = $cust_main->status;
446 $return{statuscolor} = $cust_main->statuscolor;
448 for (@cust_main_editable_fields) {
449 $return{$_} = $cust_main->get($_);
452 for (@location_editable_fields) {
453 $return{$_} = $cust_main->bill_location->get($_);
454 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
456 $return{has_ship_address} = $cust_main->has_ship_address;
457 # compatibility: some places in selfservice use this to determine
458 # if there's a ship address
459 if ( $return{has_ship_address} ) {
460 $return{ship_last} = $cust_main->last;
461 $return{ship_first} = $cust_main->first;
464 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
465 $return{payinfo} = $cust_main->paymask;
466 @return{'month', 'year'} = $cust_main->paydate_monthyear;
469 $return{'invoicing_list'} =
470 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
471 $return{'postal_invoicing'} =
472 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
474 if (scalar($conf->config('support_packages'))) {
475 my @support_services = ();
476 foreach ($cust_main->support_services) {
477 my $seconds = $_->svc_x->seconds || 0;
478 my $time_remaining = (($seconds < 0) ? '-' : '' ).
479 int(abs($seconds)/3600)."h".
480 sprintf("%02d",(abs($seconds)%3600)/60)."m";
481 my $cust_pkg = $_->cust_pkg;
484 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
485 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
486 push @support_services, { svcnum => $_->svcnum,
487 time => $time_remaining,
492 $return{support_services} = \@support_services;
495 if ( $conf->config('prepayment_discounts-credit_type') ) {
497 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
500 if ( $session->{'svcnum'} ) {
501 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
502 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
503 $return{'svcnum'} = $session->{'svcnum'};
506 } elsif ( $session->{'svcnum'} ) { #no customer record
508 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
509 or die "unknown svcnum";
510 $return{name} = $svc_acct->email;
514 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
518 return { 'error' => '',
519 'custnum' => $custnum,
525 sub customer_info_short {
528 my($context, $session, $custnum) = _custoragent_session_custnum($p);
529 return { 'error' => $session } if $context eq 'error';
533 my $conf = new FS::Conf;
535 if ( $custnum ) { #customer record
537 my $search = { 'custnum' => $custnum };
538 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
539 my $cust_main = qsearchs('cust_main', $search )
540 or return { 'error' => "unknown custnum $custnum" };
542 $return{display_custnum} = $cust_main->display_custnum;
544 $return{countrydefault} = scalar($conf->config('countrydefault'));
546 $return{small_custview} =
547 small_custview( $cust_main,
548 $return{countrydefault},
552 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
554 $return{payby} = $cust_main->payby;
556 #none of these are terribly expensive if we want 'em...
557 for (@cust_main_editable_fields) {
558 $return{$_} = $cust_main->get($_);
560 #maybe a little more expensive, but it should be cached by now
561 for (@location_editable_fields) {
562 $return{$_} = $cust_main->bill_location->get($_);
563 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
566 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
567 $return{payinfo} = $cust_main->paymask;
568 @return{'month', 'year'} = $cust_main->paydate_monthyear;
571 $return{'invoicing_list'} =
572 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
573 #$return{'postal_invoicing'} =
574 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
576 if ( $session->{'svcnum'} ) {
577 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
578 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
579 $return{'svcnum'} = $session->{'svcnum'};
582 } elsif ( $session->{'svcnum'} ) { #no customer record
584 #uuh, not supproted yet... die?
585 return { 'error' => 'customer_info_short not yet supported as agent' };
589 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
593 return { 'error' => '',
594 'custnum' => $custnum,
599 sub billing_history {
602 my($context, $session, $custnum) = _custoragent_session_custnum($p);
603 return { 'error' => $session } if $context eq 'error';
605 return { 'error' => 'No customer' } unless $custnum;
607 my $search = { 'custnum' => $custnum };
608 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
609 my $cust_main = qsearchs('cust_main', $search )
610 or return { 'error' => "unknown custnum $custnum" };
614 if ( $session->{'pkgnum'} ) {
615 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
616 #next_bill_date from cust_pkg?
617 return { 'error' => 'No history for package' };
620 $return{balance} = $cust_main->balance;
621 $return{next_bill_date} = $cust_main->next_bill_date;
622 $return{next_bill_date_pretty} =
623 time2str('%m/%d/%Y', $return{next_bill_date} );
627 my $conf = new FS::Conf;
629 if ( $conf->exists('selfservice-billing_history-line_items') ) {
631 foreach my $cust_bill ( $cust_main->cust_bill ) {
634 'type' => 'Line item',
635 'description' => $_->desc. ( $_->sdate && $_->edate
636 ? ' '. time2str('%d-%b-%Y', $_->sdate).
637 ' To '. time2str('%d-%b-%Y', $_->edate)
640 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
641 'date' => $cust_bill->_date,
642 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
644 foreach $cust_bill->cust_bill_pkg;
652 'description' => 'Invoice #'. $_->display_invnum,
653 'amount' => sprintf('%.2f', $_->charged ),
655 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
657 foreach $cust_main->cust_bill;
663 'description' => 'Payment', #XXX type
664 'amount' => sprintf('%.2f', 0 - $_->paid ),
666 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
668 foreach $cust_main->cust_pay;
672 'description' => 'Credit', #more info?
673 'amount' => sprintf('%.2f', 0 -$_->amount ),
675 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
677 foreach $cust_main->cust_credit;
681 'description' => 'Refund', #more info? type, like payment?
682 'amount' => $_->refund,
684 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
686 foreach $cust_main->cust_refund;
688 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
690 $return{'history'} = \@history;
698 my $session = _cache->get($p->{'session_id'})
699 or return { 'error' => "Can't resume session" }; #better error message
701 my $custnum = $session->{'custnum'}
702 or return { 'error' => "no customer record" };
704 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
705 or return { 'error' => "unknown custnum $custnum" };
707 my $new = new FS::cust_main { $cust_main->hash };
709 $new->set( $_ => $p->{$_} )
710 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
712 if ( exists($p->{address1}) ) {
713 my $bill_location = FS::cust_location->new({
714 map { $_ => $p->{$_} } @location_editable_fields
716 # if this is unchanged from before, cust_main::replace will ignore it
717 $new->set('bill_location' => $bill_location);
720 if ( exists($p->{ship_address1}) ) {
721 my $ship_location = FS::cust_location->new({
722 map { $_ => $p->{"ship_$_"} } @location_editable_fields
724 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
725 # Selfservice unfortunately tries to indicate "same as billing
726 # address" by sending all fields empty. Did this ever work?
727 $ship_location = $cust_main->bill_location;
729 $new->set('ship_location' => $ship_location);
731 # but if it hasn't been passed in at all, leave ship_location alone--
732 # DON'T change it to match bill_location.
735 if (exists($p->{'payby'})) {
736 $p->{'payby'} =~ /^([A-Z]{4})$/
737 or return { 'error' => "illegal_payby " . $p->{'payby'} };
741 if ( $payby =~ /^(CARD|DCRD)$/ ) {
743 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
745 if ( $new->payinfo eq $cust_main->paymask ) {
746 $new->payinfo($cust_main->payinfo);
748 $new->payinfo($p->{'payinfo'});
751 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
753 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
756 $p->{'payinfo1'} =~ /^([\dx]+)$/
757 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
759 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
760 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
762 $payinfo = $payinfo1. '@'. $payinfo2;
764 $new->payinfo( ($payinfo eq $cust_main->paymask)
765 ? $cust_main->payinfo
769 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
771 } elsif ( $payby =~ /^(BILL)$/ ) {
773 } elsif ( $payby ) { #notyet ready
774 return { 'error' => "unknown payby $payby" };
778 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
779 #false laziness with httemplate/edit/process/cust_main.cgi
780 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
781 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
783 @invoicing_list = $cust_main->invoicing_list;
786 my $error = $new->replace($cust_main, \@invoicing_list);
787 return { 'error' => $error } if $error;
790 return { 'error' => '' };
795 my $session = _cache->get($p->{'session_id'})
796 or return { 'error' => "Can't resume session" }; #better error message
802 my $conf = new FS::Conf;
803 use vars qw($payment_info); #cache for performance
804 unless ( $payment_info ) {
806 my %states = map { $_->state => 1 }
807 qsearch('cust_main_county', {
808 'country' => $conf->config('countrydefault') || 'US'
811 my %cust_paybys = map { $_ => 1 }
812 map { FS::payby->payby2payment($_) }
813 $conf->config('signup_server-payby');
815 my @cust_paybys = keys %cust_paybys;
819 #list all counties/states/countries
820 'cust_main_county' =>
821 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
823 #shortcut for one-country folks
825 [ sort { $a cmp $b } keys %states ],
827 'card_types' => card_types(),
829 'paytypes' => [ @FS::cust_main::paytypes ],
831 'paybys' => [ $conf->config('signup_server-payby') ],
832 'cust_paybys' => \@cust_paybys,
834 'stateid_label' => FS::Msgcat::_gettext('stateid'),
835 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
837 'show_ss' => $conf->exists('show_ss'),
838 'show_stateid' => $conf->exists('show_stateid'),
839 'show_paystate' => $conf->exists('show_bankstate'),
841 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
843 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
852 my %return = %$payment_info;
854 my $custnum = $session->{'custnum'};
856 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
857 or return { 'error' => "unknown custnum $custnum" };
859 $return{'hide_payment_fields'} = [
861 my $pg = payment_gateway($cust_main, $_);
862 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
863 } @{ $return{cust_paybys} }
866 $return{balance} = $cust_main->balance; #XXX pkg-balances?
868 $return{payname} = $cust_main->payname
869 || ( $cust_main->first. ' '. $cust_main->get('last') );
871 $return{$_} = $cust_main->bill_location->get($_)
872 for qw(address1 address2 city state zip);
874 $return{payby} = $cust_main->payby;
875 $return{stateid_state} = $cust_main->stateid_state;
877 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
878 $return{card_type} = cardtype($cust_main->payinfo);
879 $return{payinfo} = $cust_main->paymask;
881 @return{'month', 'year'} = $cust_main->paydate_monthyear;
885 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
886 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
887 $return{payinfo1} = $payinfo1;
888 $return{payinfo2} = $payinfo2;
889 $return{paytype} = $cust_main->paytype;
890 $return{paystate} = $cust_main->paystate;
891 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
894 if ( $conf->config('prepayment_discounts-credit_type') ) {
896 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
899 #doubleclick protection
901 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
903 return { 'error' => '',
909 #some false laziness with httemplate/process/payment.cgi - look there for
910 #ACH and CVV support stuff
912 sub validate_payment {
915 my $session = _cache->get($p->{'session_id'})
916 or return { 'error' => "Can't resume session" }; #better error message
918 my $custnum = $session->{'custnum'};
920 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
921 or return { 'error' => "unknown custnum $custnum" };
923 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
924 or return { 'error' => gettext('illegal_amount') };
926 return { error => 'Amount must be greater than 0' } unless $amount > 0;
928 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
929 #changing the hidden form values
930 my $conf = new FS::Conf;
931 my $fee_display = $conf->config('selfservice_process-display') || 'add';
932 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart');
933 if ( $fee_display eq 'add' && $fee_pkgpart ) {
934 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
935 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
938 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
939 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
940 my $discount_term = $1;
942 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
943 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
946 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
947 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
950 $p->{'payby'} ||= 'CARD';
951 $p->{'payby'} =~ /^([A-Z]{4})$/
952 or return { 'error' => "illegal_payby " . $p->{'payby'} };
955 #false laziness w/process/payment.cgi
958 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
960 $p->{'payinfo1'} =~ /^([\dx]+)$/
961 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
963 $p->{'payinfo2'} =~ /^([\dx]+)$/
964 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
966 $payinfo = $payinfo1. '@'. $payinfo2;
968 $payinfo = $cust_main->payinfo
969 if $cust_main->paymask eq $payinfo;
971 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
973 $payinfo = $p->{'payinfo'};
975 #more intelligent matching will be needed here if you change
976 #card_masking_method and don't remove existing paymasks
977 $payinfo = $cust_main->payinfo
978 if $cust_main->paymask eq $payinfo;
981 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
982 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
986 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
987 return { 'error' => gettext('unknown_card_type') }
988 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
990 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
991 if ( cardtype($payinfo) eq 'American Express card' ) {
992 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
993 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
996 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
997 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1003 die "unknown payby $payby";
1006 my %payby2fields = (
1007 'CARD' => [ qw( paystart_month paystart_year payissue payip
1008 address1 address2 city state zip country ) ],
1009 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1013 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1016 'cust_main' => $cust_main, #XXX or just custnum??
1017 'amount' => $amount,
1019 'payinfo' => $payinfo,
1020 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1021 'card_type' => $card_type,
1022 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1023 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1024 'month' => $p->{'month'},
1025 'year' => $p->{'year'},
1026 'payname' => $payname,
1027 'paybatch' => $paybatch, #this doesn't actually do anything
1028 'paycvv' => $paycvv,
1029 'payname' => $payname,
1030 'discount_term' => $discount_term,
1031 'pkgnum' => $session->{'pkgnum'},
1032 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1042 my $validate = validate_payment($p);
1043 return $validate if $validate->{'error'};
1045 my $conf = new FS::Conf;
1046 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1047 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1049 +{ map { $_=>$validate->{$_} }
1050 qw( card_type paymask payname paydate_pretty month year amount
1051 address1 address2 city state zip country
1057 sub process_stored_payment {
1060 my $session_id = $p->{'session_id'};
1062 my $payment_info = _cache->get( "payment_$session_id" )
1063 or return { 'error' => "Can't resume session" }; #better error message
1065 do_process_payment($payment_info);
1069 sub process_payment {
1072 my $payment_info = validate_payment($p);
1073 return $payment_info if $payment_info->{'error'};
1075 do_process_payment($payment_info);
1079 sub do_process_payment {
1080 my $validate = shift;
1082 my $cust_main = $validate->{'cust_main'};
1084 my $amount = delete $validate->{'amount'};
1087 my $payby = delete $validate->{'payby'};
1089 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1092 'paynum_ref' => \$paynum,
1095 return { 'error' => $error } if $error;
1097 #no error, so order the fee package if applicable...
1098 my $conf = new FS::Conf;
1099 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart');
1100 if ( $fee_pkgpart ) {
1102 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1104 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1105 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1108 #and generate an invoice for it now too
1109 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1110 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1115 $cust_main->apply_payments;
1117 if ( $validate->{'save'} ) {
1118 my $new = new FS::cust_main { $cust_main->hash };
1119 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1120 $new->set( $_ => $validate->{$_} )
1121 foreach qw( payname paystart_month paystart_year payissue payip );
1122 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1124 my $bill_location = FS::cust_location->new({
1125 map { $_ => $validate->{$_} }
1126 qw(address1 address2 city state country zip)
1128 $new->set('bill_location' => $bill_location);
1129 # but don't allow the service address to change this way.
1131 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1132 $new->set( $_ => $validate->{$_} )
1133 foreach qw( payname payip paytype paystate
1134 stateid stateid_state );
1135 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1137 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1138 $new->set( 'paydate' => $validate->{'paydate'} );
1139 my $error = $new->replace($cust_main);
1141 #no, this causes customers to process their payments again
1142 #return { 'error' => $error };
1143 #XXX just warn verosely for now so i can figure out how these happen in
1144 # the first place, eventually should redirect them to the "change
1145 #address" page but indicate the payment did process??
1146 delete($validate->{'payinfo'}); #don't want to log this!
1147 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1148 "NEW: ". Dumper($new)."\n".
1149 "OLD: ". Dumper($cust_main)."\n".
1150 "PACKET: ". Dumper($validate)."\n";
1158 my $receipt_html = '';
1160 # currently supported for realtime CC only; send receipt data to SS
1161 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1164 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1167 <TD ALIGN="right">Payment#</TD>
1168 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1172 <TD ALIGN="right">Date</TD>
1174 <TD BGCOLOR="#FFFFFF"><B>! .
1175 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1181 <TD ALIGN="right">Amount</TD>
1182 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1187 <TD ALIGN="right">Payment method</TD>
1188 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1199 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1203 'amount' => sprintf('%.2f', $cust_pay->paid),
1204 'date' => $cust_pay->_date,
1205 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1206 'time_pretty' => time2str('%T', $cust_pay->_date),
1207 'auth_num' => $auth,
1208 'order_num' => $order,
1209 'receipt_html' => $receipt_html,
1216 'receipt_html' => '',
1223 sub realtime_collect {
1226 my $session = _cache->get($p->{'session_id'})
1227 or return { 'error' => "Can't resume session" }; #better error message
1229 my $custnum = $session->{'custnum'};
1231 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1232 or return { 'error' => "unknown custnum $custnum" };
1235 if ( $p->{'amount'} ) {
1236 $amount = $p->{'amount'};
1238 elsif ( $session->{'pkgnum'} ) {
1239 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1242 $amount = $cust_main->balance;
1245 my $error = $cust_main->realtime_collect(
1246 'method' => $p->{'method'},
1247 'amount' => $amount,
1248 'pkgnum' => $session->{'pkgnum'},
1249 'session_id' => $p->{'session_id'},
1253 return { 'error' => $error } unless ref( $error );
1255 return { 'error' => '', amount => $amount, %$error };
1258 sub process_payment_order_pkg {
1261 my $hr = process_payment($p);
1262 return $hr if $hr->{'error'};
1267 sub process_payment_order_renew {
1270 my $hr = process_payment($p);
1271 return $hr if $hr->{'error'};
1276 sub process_prepay {
1280 my $session = _cache->get($p->{'session_id'})
1281 or return { 'error' => "Can't resume session" }; #better error message
1285 my $custnum = $session->{'custnum'};
1287 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1288 or return { 'error' => "unknown custnum $custnum" };
1290 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1291 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1299 return { 'error' => $error } if $error;
1301 return { 'error' => '',
1302 'amount' => $amount,
1303 'seconds' => $seconds,
1304 'duration' => duration_exact($seconds),
1305 'upbytes' => $upbytes,
1306 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1307 'downbytes' => $downbytes,
1308 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1309 'totalbytes'=> $totalbytes,
1310 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1317 my $session = _cache->get($p->{'session_id'})
1318 or return { 'error' => "Can't resume session" }; #better error message
1320 my $custnum = $session->{'custnum'};
1322 my $invnum = $p->{'invnum'};
1324 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1325 'custnum' => $custnum } )
1326 or return { 'error' => "Can't find invnum" };
1330 return { 'error' => '',
1331 'invnum' => $invnum,
1332 'invoice_text' => join('', $cust_bill->print_text ),
1333 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1340 my $session = _cache->get($p->{'session_id'})
1341 or return { 'error' => "Can't resume session" }; #better error message
1343 my $custnum = $session->{'custnum'};
1345 my $invnum = $p->{'invnum'};
1347 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1348 'custnum' => $custnum } )
1349 or return { 'error' => "Can't find invnum" };
1353 return { 'error' => '',
1354 'invnum' => $invnum,
1355 'invoice_pdf' => $cust_bill->print_pdf({
1356 'unsquelch_cdr' => 1,
1357 'locale' => $p->{'locale'},
1363 sub legacy_invoice {
1365 my $session = _cache->get($p->{'session_id'})
1366 or return { 'error' => "Can't resume session" }; #better error message
1368 my $custnum = $session->{'custnum'};
1370 my $legacyinvnum = $p->{'legacyinvnum'};
1373 'legacyinvnum' => $legacyinvnum,
1374 'custnum' => $custnum,
1377 my $legacy_cust_bill =
1378 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1379 || qsearchs('legacy_cust_bill', \%hash )
1380 or return { 'error' => "Can't find legacyinvnum" };
1384 return { 'error' => '',
1385 'legacyinvnum' => $legacyinvnum,
1386 'legacyid' => $legacy_cust_bill->legacyid,
1387 'invoice_html' => $legacy_cust_bill->content_html,
1392 sub legacy_invoice_pdf {
1394 my $session = _cache->get($p->{'session_id'})
1395 or return { 'error' => "Can't resume session" }; #better error message
1397 my $custnum = $session->{'custnum'};
1399 my $legacyinvnum = $p->{'legacyinvnum'};
1401 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1402 'legacyinvnum' => $legacyinvnum,
1403 'custnum' => $custnum,
1404 }) or return { 'error' => "Can't find legacyinvnum" };
1408 return { 'error' => '',
1409 'legacyinvnum' => $legacyinvnum,
1410 'legacyid' => $legacy_cust_bill->legacyid,
1411 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1419 #sessioning for this? how do we get the session id to the backend invoice
1420 # template so it can add it to the link, blah
1423 if ( $p->{'invnum'} ) {
1424 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1425 or return { 'error' => 'unknown invnum' };
1426 $agentnum = $cust_bill->cust_main->agentnum;
1429 my $templatename = $p->{'template'} || $p->{'templatename'};
1431 #false laziness-ish w/view/cust_bill-logo.cgi
1433 my $conf = new FS::Conf;
1434 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1435 $templatename = "_$1";
1440 my $filename = "logo$templatename.png";
1442 return { 'error' => '',
1443 'logo' => $conf->config_binary($filename, $agentnum),
1444 'content_type' => 'image/png', #should allow gif, jpg too
1451 my $session = _cache->get($p->{'session_id'})
1452 or return { 'error' => "Can't resume session" }; #better error message
1454 my $custnum = $session->{'custnum'};
1456 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1457 or return { 'error' => "unknown custnum $custnum" };
1459 my $conf = new FS::Conf;
1461 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1463 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1467 return { 'error' => '',
1468 'balance' => $cust_main->balance,
1471 my $owed = $_->owed;
1473 +{ 'invnum' => $_->invnum,
1474 '_date' => $_->_date,
1475 'date' => time2str("%b %o, %Y", $_->_date),
1476 'date_short' => time2str("%m-%d-%Y", $_->_date),
1477 'previous' => sprintf('%.2f', ($_->previous)[0]),
1478 'charged' => sprintf('%.2f', $_->charged),
1479 'owed' => sprintf('%.2f', $owed),
1480 'balance' => sprintf('%.2f', $balance),
1485 'legacy_invoices' => [
1487 +{ 'legacyinvnum' => $_->legacyinvnum,
1488 'legacyid' => $_->legacyid,
1489 '_date' => $_->_date,
1490 'date' => time2str("%b %o, %Y", $_->_date),
1491 'date_short' => time2str("%m-%d-%Y", $_->_date),
1492 'charged' => sprintf('%.2f', $_->charged),
1493 'has_content' => ( length($_->content_pdf)
1494 || length($_->content_html) ),
1504 my $session = _cache->get($p->{'session_id'})
1505 or return { 'error' => "Can't resume session" }; #better error message
1507 my $custnum = $session->{'custnum'};
1509 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1510 or return { 'error' => "unknown custnum $custnum" };
1512 my @errors = $cust_main->cancel( 'quiet'=>1 );
1514 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1516 return { 'error' => $error };
1523 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1524 return { 'error' => $session } if $context eq 'error';
1526 my $search = { 'custnum' => $custnum };
1527 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1528 my $cust_main = qsearchs('cust_main', $search )
1529 or return { 'error' => "unknown custnum $custnum" };
1531 my $conf = new FS::Conf;
1533 # the duplication below is necessary:
1534 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1535 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1536 # non-backwards-compatible change breaking the software of anyone using the API
1537 # instead of the stock selfservice
1538 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1539 if( $conf->exists('selfservice_server-view-wholesale') ) {
1540 return { 'svcnum' => $session->{'svcnum'},
1541 'custnum' => $custnum,
1542 'cust_pkg' => [ map {
1544 part_pkg => [ map $_->hashref, $_->part_pkg ],
1546 [ map $_->hashref, $_->available_part_svc ],
1548 [ map { my $ref = { $_->hash,
1549 label => [ $_->label ],
1551 $ref->{_password} = $_->svc_x->_password
1552 if $context eq 'agent'
1553 && $conf->exists('agent-showpasswords')
1554 && $_->part_svc->svcdb eq 'svc_acct';
1559 } $cust_main->cust_pkg
1562 small_custview( $cust_main, $conf->config('countrydefault') ),
1563 'wholesale_view' => 1,
1564 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1565 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1566 'lnp' => $conf->exists('svc_phone-lnp'),
1570 { 'svcnum' => $session->{'svcnum'},
1571 'custnum' => $custnum,
1572 'cust_pkg' => [ map {
1573 my $primary_cust_svc = $_->primary_cust_svc;
1576 pkg_label => $_->pkg_label,
1577 status => $_->status,
1579 [ map $_->hashref, $_->available_part_svc ],
1581 [ map { my $ref = { $_->hash,
1582 label => [ $_->label ],
1584 $ref->{_password} = $_->svc_x->_password
1585 if $context eq 'agent'
1586 && $conf->exists('agent-showpasswords')
1587 && $_->part_svc->svcdb eq 'svc_acct';
1588 $ref->{svchash} = { $_->svc_x->hash } if
1589 $_->part_svc->svcdb eq 'svc_phone';
1590 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1591 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1597 ? { $primary_cust_svc->hash,
1598 label => [ $primary_cust_svc->label ],
1599 finger => $primary_cust_svc->svc_x->finger, #uuh
1600 $primary_cust_svc->part_svc->hash,
1604 } $cust_main->ncancelled_pkgs
1607 small_custview( $cust_main, $conf->config('countrydefault') ),
1615 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1616 return { 'error' => $session } if $context eq 'error';
1618 my $search = { 'custnum' => $custnum };
1619 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1620 my $cust_main = qsearchs('cust_main', $search )
1621 or return { 'error' => "unknown custnum $custnum" };
1623 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1624 if ( ! $pkgnum && $p->{'svcnum'} ) {
1625 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1626 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1630 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1631 foreach my $cust_pkg ( $p->{'ncancelled'}
1632 ? $cust_main->ncancelled_pkgs
1633 : $cust_main->unsuspended_pkgs ) {
1634 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1635 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1638 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1640 if ( $p->{'svcdb'} ) {
1641 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1643 : ref($p->{'svcdb'}) eq 'ARRAY'
1644 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1645 : { $p->{'svcdb'} => 1 };
1646 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1649 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1652 my $conf = new FS::Conf;
1655 'svcnum' => $session->{'svcnum'},
1656 'custnum' => $custnum,
1657 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1658 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1661 my $svc_x = $_->svc_x;
1662 my($label, $value) = $_->label;
1663 my $part_svc = $_->part_svc;
1664 my $svcdb = $part_svc->svcdb;
1665 my $cust_pkg = $_->cust_pkg;
1666 my $part_pkg = $cust_pkg->part_pkg;
1669 'svcnum' => $_->svcnum,
1670 'display_svcnum' => $_->display_svcnum,
1674 'pkg_label' => $cust_pkg->pkg_label,
1675 'pkg_status' => $cust_pkg->status,
1676 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1679 if ( $svcdb eq 'svc_acct' ) {
1682 'username' => $svc_x->username,
1683 'email' => $svc_x->email,
1684 'finger' => $svc_x->finger,
1685 'seconds' => $svc_x->seconds,
1686 'upbytes' => display_bytecount($svc_x->upbytes),
1687 'downbytes' => display_bytecount($svc_x->downbytes),
1688 'totalbytes' => display_bytecount($svc_x->totalbytes),
1690 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1691 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1692 'recharge_upbytes' =>
1693 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1694 'recharge_downbytes' =>
1695 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1696 'recharge_totalbytes' =>
1697 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1701 } elsif ( $svcdb eq 'svc_dsl' ) {
1702 $hash{'phonenum'} = $svc_x->phonenum;
1703 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1704 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1705 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1708 $hash{'name'} = $cust_main->name;
1711 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1725 sub _customer_svc_x {
1726 my($custnum, $svcnum, $table) = (shift, shift, shift);
1727 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1729 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1730 my $search = " AND custnum = $1";
1731 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1734 'table' => ($table || 'svc_acct'),
1735 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1736 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1737 #'LEFT JOIN cust_main USING ( custnum ) ',
1738 'hashref' => $hashref,
1739 'extra_sql' => $search, #important
1744 sub svc_status_html {
1747 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1748 return { 'error' => $session } if $context eq 'error';
1750 #XXX only svc_dsl for now
1751 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1752 or return { 'error' => "Service not found" };
1754 my $html = $svc_x->getstatus_html;
1756 return { 'html' => $html };
1760 sub svc_status_hash {
1763 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1764 return { 'error' => $session } if $context eq 'error';
1766 #XXX only svc_acct for now
1767 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1768 or return { 'error' => "Service not found" };
1770 my ( $html, $hashref ) = $svc_x->export_getstatus;
1775 sub set_svc_status_hash {
1778 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1779 return { 'error' => $session } if $context eq 'error';
1781 #XXX only svc_acct for now
1782 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1783 or return { 'error' => "Service not found" };
1785 warn "set_svc_status_hash ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1787 my $error = $svc_x->export_setstatus($p); #$p? returns error?
1788 return { 'error' => $error } if $error;
1790 return {}; #? { 'error' => '' }
1795 sub acct_forward_info {
1798 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1799 return { 'error' => $session } if $context eq 'error';
1801 my $svc_forward = _customer_svc_x( $custnum,
1802 { 'srcsvc' => $p->{'svcnum'} },
1805 or return { 'error' => '',
1809 return { 'error' => '',
1810 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1815 sub process_acct_forward {
1817 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1818 return { 'error' => $session } if $context eq 'error';
1820 my $old = _customer_svc_x( $custnum,
1821 { 'srcsvc' => $p->{'svcnum'} },
1825 if ( $p->{'dst'} eq '' ) {
1827 my $error = $old->delete;
1828 return { 'error' => $error };
1830 return { 'error' => '' };
1833 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1834 'dst' => $p->{'dst'},
1839 $new->svcnum($old->svcnum);
1840 my $cust_svc = $old->cust_svc;
1841 $new->svcpart($old->svcpart);
1842 $new->pkgnuym($old->pkgnum);
1843 $error = $new->replace($old);
1845 my $conf = new FS::Conf;
1846 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1848 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1849 or return { 'error' => 'No service' }; #how would we even get here?
1851 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1853 $error = $new->insert;
1856 return { 'error' => $error };
1860 sub list_dsl_devices {
1863 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1864 return { 'error' => $session } if $context eq 'error';
1866 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1867 or return { 'error' => "Service not found" };
1870 'devices' => [ map {
1871 +{ 'mac_addr' => $_->mac_addr };
1872 } $svc_dsl->dsl_device
1878 sub add_dsl_device {
1881 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1882 return { 'error' => $session } if $context eq 'error';
1884 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1885 or return { 'error' => "Service not found" };
1887 return { 'error' => 'No MAC address supplied' }
1888 unless length($p->{'mac_addr'});
1890 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1891 'mac_addr' => scalar($p->{'mac_addr'}),
1893 my $error = $dsl_device->insert;
1894 return { 'error' => $error };
1898 sub delete_dsl_device {
1901 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1902 return { 'error' => $session } if $context eq 'error';
1904 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1905 or return { 'error' => "Service not found" };
1907 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
1908 'mac_addr' => scalar($p->{'mac_addr'}),
1911 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1913 my $error = $dsl_device->delete;
1914 return { 'error' => $error };
1920 _usage_details( \&_port_graph, $p,
1921 'svcdb' => 'svc_port',
1926 my($svc_port, $begin, $end) = @_;
1928 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1929 push @usage, { 'png' => $pngOrError };
1933 sub _list_svc_usage {
1934 my($svc_acct, $begin, $end) = @_;
1936 foreach my $part_export (
1937 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1938 qw( sqlradius sqlradius_withdomain )
1940 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1945 sub list_svc_usage {
1946 _usage_details(\&_list_svc_usage, @_);
1949 sub _list_support_usage {
1950 my($svc_acct, $begin, $end) = @_;
1952 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1953 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1955 push @usage, { 'seconds' => $_->seconds,
1956 'support' => $_->support,
1957 '_date' => $_->_date,
1958 'id' => $_->transaction_id,
1959 'creator' => $_->creator,
1960 'subject' => $_->subject,
1961 'status' => $_->status,
1962 'ticketid' => $_->ticketid,
1968 sub list_support_usage {
1969 _usage_details(\&_list_support_usage, @_);
1972 sub _list_cdr_usage {
1973 # XXX CDR type support...
1974 # XXX any way to do a paged search on this?
1975 # we have to return the results all at once...
1976 my($svc_phone, $begin, $end, %opt) = @_;
1977 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
1978 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1981 sub list_cdr_usage {
1983 _usage_details( \&_list_cdr_usage, $p,
1984 'svcdb' => 'svc_phone',
1988 sub _usage_details {
1989 my($callback, $p, %opt) = @_;
1991 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1992 return { 'error' => $session } if $context eq 'error';
1994 my $search = { 'svcnum' => $p->{'svcnum'} };
1995 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1997 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1999 my $svc_x = qsearchs( $svcdb, $search );
2000 return { 'error' => 'No service selected in list_svc_usage' }
2003 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2004 my $freq = $cust_pkg->part_pkg->freq;
2007 if ( $svcdb eq 'svc_phone' ) {
2008 my $format = $cust_pkg->part_pkg->option('output_format') || '';
2009 $format = '' if $format =~ /^sum_/;
2010 # sensible default if there is no format or it's a summary format
2011 if ( $cust_pkg->part_pkg->plan eq 'voip_inbound' ) {
2012 $format ||= 'source_default';
2013 $callback_opt{inbound} = 1;
2016 $format ||= 'default';
2019 $callback_opt{format} = $format;
2020 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2023 my $start = $cust_pkg->setup;
2024 #my $end = $cust_pkg->bill; # or time?
2027 unless ( $p->{beginning} ) {
2028 $p->{beginning} = $cust_pkg->last_bill;
2029 $p->{ending} = $end;
2032 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2036 #kinda false laziness with FS::cust_main::bill, but perhaps
2037 #we should really change this bit to DateTime and DateTime::Duration
2039 #change this bit to use Date::Manip? CAREFUL with timezones (see
2040 # mailing list archive)
2041 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2042 (localtime($p->{ending}) )[0,1,2,3,4,5];
2043 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2044 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2046 if ( $freq =~ /^\d+$/ ) {
2048 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2050 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2051 } elsif ( $freq =~ /^(\d+)w$/ ) {
2053 $nmday += $weeks * 7;
2054 $pmday -= $weeks * 7;
2055 } elsif ( $freq =~ /^(\d+)d$/ ) {
2059 } elsif ( $freq =~ /^(\d+)h$/ ) {
2064 return { 'error' => "unparsable frequency: ". $freq };
2067 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2068 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2072 'svcnum' => $p->{svcnum},
2073 'beginning' => $p->{beginning},
2074 'ending' => $p->{ending},
2075 'previous' => ($previous > $start) ? $previous : $start,
2076 'next' => ($next < $end) ? $next : $end,
2077 'header' => $header,
2085 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2086 return { 'error' => $session } if $context eq 'error';
2088 my $search = { 'custnum' => $custnum };
2089 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2090 my $cust_main = qsearchs('cust_main', $search )
2091 or return { 'error' => "unknown custnum $custnum" };
2093 my $status = $cust_main->status;
2094 #false laziness w/ClientAPI/Signup.pm
2096 my $cust_pkg = new FS::cust_pkg ( {
2097 'custnum' => $custnum,
2098 'pkgpart' => $p->{'pkgpart'},
2100 my $error = $cust_pkg->check;
2101 return { 'error' => $error } if $error;
2104 unless ( $p->{'svcpart'} eq 'none' ) {
2108 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2110 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2111 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2112 $svcdb = $part_svc->svcdb;
2114 $svcdb = 'svc_acct';
2116 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2119 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2120 'svc_domain' => [ qw( domain ) ],
2121 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2122 'svc_external' => [ qw( id title ) ],
2123 'svc_pbx' => [ qw( id title ) ],
2126 my $svc_x = "FS::$svcdb"->new( {
2127 'svcpart' => $svcpart,
2128 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2131 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2134 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2135 my $acct_snarf = new FS::acct_snarf ( {
2136 'machine' => $p->{"snarf_machine$snarfnum"},
2137 'protocol' => $p->{"snarf_protocol$snarfnum"},
2138 'username' => $p->{"snarf_username$snarfnum"},
2139 '_password' => $p->{"snarf_password$snarfnum"},
2142 push @acct_snarf, $acct_snarf;
2144 $svc_x->child_objects( \@acct_snarf );
2147 my $y = $svc_x->setdefault; # arguably should be in new method
2148 return { 'error' => $y } if $y && !ref($y);
2150 $error = $svc_x->check;
2151 return { 'error' => $error } if $error;
2158 tie my %hash, 'Tie::RefHash';
2159 %hash = ( $cust_pkg => \@svc );
2161 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2162 return { 'error' => $error } if $error;
2164 my $conf = new FS::Conf;
2165 if ( $conf->exists('signup_server-realtime') ) {
2167 my $bill_error = _do_bop_realtime( $cust_main, $status );
2170 $cust_pkg->cancel('quiet'=>1);
2173 $cust_pkg->reexport;
2177 $cust_pkg->reexport;
2180 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2182 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2189 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2190 return { 'error' => $session } if $context eq 'error';
2192 my $search = { 'custnum' => $custnum };
2193 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2194 my $cust_main = qsearchs('cust_main', $search )
2195 or return { 'error' => "unknown custnum $custnum" };
2197 my $status = $cust_main->status;
2198 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2199 or return { 'error' => "unknown package $p->{pkgnum}" };
2202 my $error = FS::cust_pkg::order( $custnum,
2208 my $conf = new FS::Conf;
2209 if ( $conf->exists('signup_server-realtime') ) {
2211 my $bill_error = _do_bop_realtime( $cust_main, $status );
2214 $newpkg[0]->suspend;
2217 $newpkg[0]->reexport;
2221 $newpkg[0]->reexport;
2224 return { error => '', pkgnum => $cust_pkg->pkgnum };
2228 sub order_recharge {
2231 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2232 return { 'error' => $session } if $context eq 'error';
2234 my $search = { 'custnum' => $custnum };
2235 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2236 my $cust_main = qsearchs('cust_main', $search )
2237 or return { 'error' => "unknown custnum $custnum" };
2239 my $status = $cust_main->status;
2240 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2241 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2243 my $svc_x = $cust_svc->svc_x;
2244 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2247 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2248 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2249 recharge_totalbytes );
2250 my $amount = $part_pkg->option('recharge_amount', 1);
2252 my ($l, $v, $d) = $cust_svc->label; # blah
2253 my $pkg = "Recharge $v";
2255 my $bill_error = $cust_main->charge($amount, $pkg,
2256 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2257 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2258 $part_pkg->taxclass); #meh
2260 my $conf = new FS::Conf;
2261 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2263 $bill_error = _do_bop_realtime( $cust_main, $status );
2268 my $error = $svc_x->recharge (\%vhash);
2269 return { 'error' => $error } if $error;
2273 my $error = $bill_error;
2274 $error ||= $svc_x->recharge (\%vhash);
2275 return { 'error' => $error } if $error;
2278 return { error => '', svc => $cust_svc->part_svc->svc };
2282 sub _do_bop_realtime {
2283 my ($cust_main, $status) = (shift, shift);
2285 my $old_balance = $cust_main->balance;
2287 my $bill_error = $cust_main->bill
2288 || $cust_main->apply_payments_and_credits
2289 || $cust_main->realtime_collect('selfservice' => 1);
2291 if ( $cust_main->balance > $old_balance
2292 && $cust_main->balance > 0
2293 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2294 1 : $status eq 'suspended' ) ) {
2295 #this makes sense. credit is "un-doing" the invoice
2296 my $conf = new FS::Conf;
2297 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2298 'self-service decline',
2299 'reason_type' => $conf->config('signup_credit_type'),
2301 $cust_main->apply_credits( 'order' => 'newest' );
2303 return { 'error' => '_decline', 'bill_error' => $bill_error };
2312 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2313 return { 'error' => $session } if $context eq 'error';
2315 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2316 or return { 'error' => "unknown custnum $custnum" };
2318 my @cust_pkg = sort { $a->bill <=> $b->bill }
2319 grep { $_->part_pkg->freq ne '0' }
2320 $cust_main->ncancelled_pkgs;
2322 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2324 my $total = $cust_main->balance;
2327 my $bill = $_->bill;
2328 $total += $_->part_pkg->base_recur($_, \$bill);
2329 my $renew_date = $_->part_pkg->add_freq($_->bill);
2331 'pkgnum' => $_->pkgnum,
2332 'amount' => sprintf('%.2f', $total),
2333 'bill_date' => $_->bill,
2334 'bill_date_pretty' => time2str('%x', $_->bill),
2335 'renew_date' => $renew_date,
2336 'renew_date_pretty' => time2str('%x', $renew_date),
2337 'expire_date' => $_->expire,
2338 'expire_date_pretty' => time2str('%x', $_->expire),
2343 return { 'dates' => \@array };
2347 sub payment_info_renew_info {
2349 my $renew_info = renew_info($p);
2350 my $payment_info = payment_info($p);
2351 return { %$renew_info,
2359 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2360 return { 'error' => $session } if $context eq 'error';
2362 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2363 or return { 'error' => "unknown custnum $custnum" };
2365 my $date = $p->{'date'};
2369 #freeside-daily -n -d $date fs_daily $custnum
2370 $cust_main->bill_and_collect( 'time' => $date,
2371 'invoice_time' => $now,
2372 'actual_time' => $now,
2373 'check_freq' => '1d',
2376 return { 'error' => '' };
2382 my $session = _cache->get($p->{'session_id'})
2383 or return { 'error' => "Can't resume session" }; #better error message
2385 my $custnum = $session->{'custnum'};
2387 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2388 or return { 'error' => "unknown custnum $custnum" };
2390 my $conf = new FS::Conf;
2392 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2393 or return { 'error' => 'Permission denied' };
2395 my $pkgnum = $p->{'pkgnum'};
2397 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2398 'pkgnum' => $pkgnum, } )
2399 or return { 'error' => "unknown pkgnum $pkgnum" };
2401 my $error = $cust_pkg->suspend(reason => $reasonnum);
2402 return { 'error' => $error };
2408 my $session = _cache->get($p->{'session_id'})
2409 or return { 'error' => "Can't resume session" }; #better error message
2411 my $custnum = $session->{'custnum'};
2413 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2414 or return { 'error' => "unknown custnum $custnum" };
2416 my $pkgnum = $p->{'pkgnum'};
2418 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2419 'pkgnum' => $pkgnum, } )
2420 or return { 'error' => "unknown pkgnum $pkgnum" };
2422 my $error = $cust_pkg->cancel('quiet' => 1);
2423 return { 'error' => $error };
2427 sub provision_phone {
2430 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2432 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2433 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2434 return { 'error' => $session } if $context eq 'error';
2436 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2437 return { 'error' => 'service not found' } unless $svc_phone;
2438 return { 'error' => 'invalid svcnum' }
2439 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2441 $svc_phone->email($p->{'email'})
2442 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2443 $svc_phone->forwarddst($p->{'forwarddst'})
2444 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2445 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2446 return { 'error' => $svc_phone->replace };
2450 unless($p->{'lnp'}) {
2451 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2452 $p->{'lnp_status'} = "portingin";
2453 return _provision( 'FS::svc_phone',
2454 [qw(lnp_desired_due_date lnp_other_provider
2455 lnp_other_provider_account phonenum countrycode lnp_status)],
2456 [qw(phonenum countrycode)],
2463 unless (scalar(@bulkdid)) {
2464 return _provision( 'FS::svc_phone',
2465 [qw(phonenum countrycode)],
2466 [qw(phonenum countrycode)],
2472 # bulk DID order case
2474 foreach my $did ( @bulkdid ) {
2475 $did =~ s/[^0-9]//g;
2476 $error = _provision( 'FS::svc_phone',
2477 [qw(phonenum countrycode)],
2478 [qw(phonenum countrycode)],
2480 'pkgnum' => $p->{'pkgnum'},
2481 'svcpart' => $p->{'svcpart'},
2483 'countrycode' => $p->{'countrycode'},
2484 'session_id' => $p->{'session_id'},
2487 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2489 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2492 sub provision_acct {
2494 warn "provision_acct called\n"
2497 return { 'error' => gettext('passwords_dont_match') }
2498 if $p->{'_password'} ne $p->{'_password2'};
2499 return { 'error' => gettext('empty_password') }
2500 unless length($p->{'_password'});
2502 if ($p->{'domsvc'}) {
2503 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2504 qw ( svcpart pkgnum ) );
2505 return { 'error' => gettext('invalid_domain') }
2506 unless ($domains{$p->{'domsvc'}});
2509 warn "provision_acct calling _provision\n"
2511 _provision( 'FS::svc_acct',
2512 [qw(username _password domsvc)],
2513 [qw(username _password domsvc)],
2519 sub provision_external {
2521 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2522 _provision( 'FS::svc_external',
2531 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2532 warn "_provision called for $class\n"
2535 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2536 return { 'error' => $session } if $context eq 'error';
2538 my $search = { 'custnum' => $custnum };
2539 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2540 my $cust_main = qsearchs('cust_main', $search )
2541 or return { 'error' => "unknown custnum $custnum" };
2543 my $pkgnum = $p->{'pkgnum'};
2545 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2547 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2548 'pkgnum' => $pkgnum,
2550 or return { 'error' => "unknown pkgnum $pkgnum" };
2552 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2554 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2555 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2557 warn "creating $class record\n"
2559 my $svc_x = $class->new( {
2560 'pkgnum' => $p->{'pkgnum'},
2561 'svcpart' => $p->{'svcpart'},
2562 map { $_ => $p->{$_} } @$fields
2564 warn "inserting $class record\n"
2566 my $error = $svc_x->insert;
2569 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2571 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2574 my $return = { 'svc' => $part_svc->svc,
2576 map { $_ => $svc_x->get($_) } @$return_fields
2578 warn "_provision returning ". Dumper($return). "\n"
2587 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2588 return { 'error' => $session } if $context eq 'error';
2590 my $search = { 'custnum' => $custnum };
2591 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2592 my $cust_main = qsearchs('cust_main', $search )
2593 or return { 'error' => "unknown custnum $custnum" };
2595 my $pkgnum = $p->{'pkgnum'};
2597 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2598 'pkgnum' => $pkgnum,
2600 or return { 'error' => "unknown pkgnum $pkgnum" };
2602 my $svcpart = $p->{'svcpart'};
2604 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2605 'svcpart' => $svcpart, } )
2606 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2607 my $part_svc = $pkg_svc->part_svc;
2609 my $conf = new FS::Conf;
2612 'svc' => $part_svc->svc,
2613 'svcdb' => $part_svc->svcdb,
2614 'pkgnum' => $pkgnum,
2615 'svcpart' => $svcpart,
2616 'custnum' => $custnum,
2618 'security_phrase' => 0, #XXX !
2619 'svc_acct_pop' => [], #XXX !
2621 'init_popstate' => '',
2626 small_custview( $cust_main, $conf->config('countrydefault') ),
2630 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2631 && $ret->{'svcdb'} eq 'svc_phone') {
2632 $ret->{'svcnum'} = $p->{'svcnum'};
2633 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2634 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2635 $ret->{'email'} = $svc_phone->email;
2636 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2643 sub unprovision_svc {
2646 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2647 return { 'error' => $session } if $context eq 'error';
2649 my $search = { 'custnum' => $custnum };
2650 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2651 my $cust_main = qsearchs('cust_main', $search )
2652 or return { 'error' => "unknown custnum $custnum" };
2654 my $svcnum = $p->{'svcnum'};
2656 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2657 or return { 'error' => "unknown svcnum $svcnum" };
2659 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2660 unless $cust_svc->cust_pkg->custnum == $custnum;
2662 my $conf = new FS::Conf;
2664 return { 'svc' => $cust_svc->part_svc->svc,
2665 'error' => $cust_svc->cancel,
2667 small_custview( $cust_main, $conf->config('countrydefault') ),
2672 sub myaccount_passwd {
2674 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2675 return { 'error' => $session } if $context eq 'error';
2677 return { 'error' => "New passwords don't match." }
2678 if $p->{'new_password'} ne $p->{'new_password2'};
2680 return { 'error' => 'Enter new password' }
2681 unless length($p->{'new_password'});
2683 #my $search = { 'custnum' => $custnum };
2684 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2685 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2686 my $search = " AND custnum = $1";
2687 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2689 my $svc_acct = qsearchs( {
2690 'table' => 'svc_acct',
2691 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2692 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2693 'LEFT JOIN cust_main USING ( custnum ) ',
2694 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2695 'extra_sql' => $search, #important
2697 or return { 'error' => "Service not found" };
2699 if ( exists($p->{'old_password'}) ) {
2700 return { 'error' => "Incorrect password." }
2701 unless $svc_acct->check_password($p->{'old_password'});
2704 $svc_acct->set_password($p->{'new_password'});
2705 my $error = $svc_acct->replace();
2707 my($label, $value) = $svc_acct->cust_svc->label;
2709 return { 'error' => $error,
2719 my $conf = new FS::Conf;
2720 my $verification = $conf->config('selfservice-password_reset_verification')
2721 or return { 'error' => 'Password resets disabled' };
2723 my $username = $p->{'username'};
2725 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2726 or return { 'error' => 'Account not found' };
2728 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2729 'domsvc' => $svc_domain->svcnum }
2731 or return { 'error' => 'Account not found' };
2733 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2734 or return { 'error' => 'Account not found' };
2736 my $cust_main = $cust_pkg->cust_main;
2740 my( $p, $cust_main ) = @_;
2741 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2742 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2745 my( $p, $cust_main ) = @_;
2746 my $cust_pay = qsearchs({
2747 'table' => 'cust_pay',
2748 'hashref' => { 'custnum' => $cust_main->custnum },
2749 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2753 $p->{'amount'} == $cust_pay->paid;
2756 my( $p, $cust_main ) = @_;
2757 $p->{'zip'} eq $cust_main->zip
2758 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2762 foreach my $verify ( split(',', $verification) ) {
2764 &{ $verify{$verify} }( $p, $cust_main )
2765 or return { 'error' => 'Account not found' };
2769 #okay, we're verified, now create a unique session
2771 my $reset_session = {
2772 'svcnum' => $svc_acct->svcnum,
2775 my $timeout = '1 hour'; #?
2777 my $reset_session_id;
2779 $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2780 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2782 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2786 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2787 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2788 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2789 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2790 my $error = $msg_template->send( 'cust_main' => $cust_main,
2791 'object' => $svc_acct,
2792 'substitutions' => {
2793 'session_id' => $reset_session_id,
2797 return { 'error' => $error }; #????
2800 return { 'error' => '' };
2803 sub check_reset_passwd {
2806 my $conf = new FS::Conf;
2807 my $verification = $conf->config('selfservice-password_reset_verification')
2808 or return { 'error' => 'Password resets disabled' };
2810 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2811 or return { 'error' => "Can't resume session" }; #better error message
2813 my $svcnum = $reset_session->{'svcnum'};
2815 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2816 or return { 'error' => "Service not found" };
2818 return { 'error' => '',
2819 'username' => $svc_acct->username,
2824 sub process_reset_passwd {
2827 my $conf = new FS::Conf;
2828 my $verification = $conf->config('selfservice-password_reset_verification')
2829 or return { 'error' => 'Password resets disabled' };
2831 return { 'error' => "New passwords don't match." }
2832 if $p->{'new_password'} ne $p->{'new_password2'};
2834 return { 'error' => 'Enter new password' }
2835 unless length($p->{'new_password'});
2837 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2838 or return { 'error' => "Can't resume session" }; #better error message
2840 my $svcnum = $reset_session->{'svcnum'};
2842 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2843 or return { 'error' => "Service not found" };
2845 $svc_acct->set_password($p->{'new_password'});
2846 my $error = $svc_acct->replace();
2848 my($label, $value) = $svc_acct->cust_svc->label;
2850 return { 'error' => $error,
2859 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2860 return { 'error' => $session } if $context eq 'error';
2862 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2863 FS::TicketSystem->init();
2865 my $conf = new FS::Conf;
2866 my $queue = $p->{'queue'}
2867 || $conf->config('ticket_system-selfservice_queueid')
2868 || $conf->config('ticket_system-default_queueid');
2870 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2871 my $err_or_ticket = FS::TicketSystem->create_ticket(
2872 '', #create RT session based on FS CurrentUser (fs_selfservice)
2874 'custnum' => $custnum,
2875 'svcnum' => $session->{'svcnum'},
2876 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2879 if ( ref($err_or_ticket) ) {
2880 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2882 return { 'error' => '',
2883 'ticket_id' => $err_or_ticket->id,
2886 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2888 return { 'error' => $err_or_ticket };
2896 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2897 return { 'error' => $session } if $context eq 'error';
2899 return { error => 'requested format not implemented' }
2900 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2902 my $conf = new FS::Conf;
2903 my $age_threshold = 0;
2904 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2905 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2907 my $search = { 'custnum' => $custnum };
2908 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2909 my $cust_main = qsearchs('cust_main', $search )
2910 or return { 'error' => "unknown custnum $custnum" };
2912 # does it make more sense to just run one sql query for this instead of all the
2913 # insanity below? would increase performance greately for large data sets?
2915 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2916 my @part_svc = $cust_pkg->part_svc;
2917 foreach my $part_svc ( @part_svc ) {
2918 if($part_svc->svcdb eq 'svc_phone'){
2919 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2920 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2921 push @svc_phone, $cust_pkg_svc->svc_x
2922 if $cust_pkg_svc->date_inserted >= $age_threshold;
2930 my($xls_r,$xls_c) = (0,0);
2933 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2934 if($p->{'format'} eq 'csv') {
2935 $csv = new Text::CSV_XS { 'always_quote' => 1,
2938 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2939 $content .= $csv->string;
2941 elsif($p->{'format'} eq 'xls') {
2942 my $XLS1 = new IO::Scalar \$content;
2943 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2944 or return { 'error' => "Error opening .xls file: $!" };
2945 $xls = $xls_workbook->add_worksheet('DIDs');
2946 foreach ( @fields ) {
2947 $xls->write(0,$xls_c++,$_);
2952 foreach my $svc_phone ( @svc_phone ) {
2953 my @cols = map { $svc_phone->$_ } @fields;
2954 if($p->{'format'} eq 'csv') {
2955 return { 'error' => 'Unable to create CSV' }
2956 unless $csv->combine(@cols);
2957 $content .= $csv->string;
2959 elsif($p->{'format'} eq 'xls') {
2962 $xls->write($xls_r,$xls_c++,$_);
2968 $xls_workbook->close() if $p->{'format'} eq 'xls';
2970 { content => $content, format => $p->{'format'}, };
2975 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2976 return { 'error' => $session } if $context eq 'error';
2978 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2979 FS::TicketSystem->init();
2980 return { 'error' => 'get_ticket configuration error' }
2981 if $FS::TicketSystem::system ne 'RT_Internal';
2983 # check existence and ownership as part of this
2984 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2985 my $rt_session = FS::TicketSystem->session('');
2986 my $Ticket = FS::TicketSystem->get_ticket_object(
2988 ticket_id => $p->{'ticket_id'},
2991 return { 'error' => 'ticket not found' } if !$Ticket;
2993 if ( length( $p->{'subject'} || '' ) ) {
2995 if ( $p->{'subject'} ne $Ticket->Subject ) {
2996 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2997 return { 'error' => "unable to set subject: $msg" } if !$val;
3001 if(length($p->{'reply'})) {
3002 my @err_or_res = FS::TicketSystem->correspond_ticket(
3004 'ticket_id' => $p->{'ticket_id'},
3005 'content' => $p->{'reply'},
3008 return { 'error' => 'unable to reply to ticket' }
3009 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3012 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3013 my $err_or_ticket = FS::TicketSystem->get_ticket(
3015 'ticket_id' => $p->{'ticket_id'},
3018 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3019 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3021 return { 'error' => $err_or_ticket };
3024 my @custs = @{$err_or_ticket->{'custs'}};
3025 my @txns = @{$err_or_ticket->{'txns'}};
3028 # superseded by check in get_ticket_object
3029 #return { 'error' => 'invalid ticket requested' }
3030 #unless grep($_ eq $custnum, @custs);
3032 foreach my $txn ( @txns ) {
3033 push @filtered_txns, $txn
3034 if ($txn->{'type'} eq 'EmailRecord'
3035 || $txn->{'type'} eq 'Correspond'
3036 || $txn->{'type'} eq 'Create');
3039 warn "$me get_ticket: successful: \n"
3041 return { 'error' => '',
3042 'transactions' => \@filtered_txns,
3043 'ticket_fields' => $err_or_ticket->{'fields'},
3044 'ticket_id' => $p->{'ticket_id'},
3048 sub adjust_ticket_priority {
3050 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3051 return { 'error' => $session } if $context eq 'error';
3053 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3054 FS::TicketSystem->init;
3055 my $ss_priority = FS::TicketSystem->selfservice_priority;
3057 return { 'error' => 'adjust_ticket_priority configuration error' }
3058 if $FS::TicketSystem::system ne 'RT_Internal'
3061 my $values = $p->{'values'}; #hashref, id => priority value
3064 foreach my $id (keys %$values) {
3065 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3066 my $Ticket = FS::TicketSystem->get_ticket_object('',
3068 'custnum' => $custnum,
3071 $ticket_error{$id} = 'ticket not found';
3075 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3076 # We're not going to implement it for RT_External.
3077 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3078 my $new_value = $values->{$id};
3079 next if $old_value eq $new_value;
3081 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3083 # AddCustomFieldValue works fine (replacing any existing value) if it's
3084 # a single-valued custom field, which it should be. If it's not, you're
3085 # doing something wrong.
3087 if ( length($new_value) ) {
3088 ($val, $msg) = $Ticket->AddCustomFieldValue(
3089 Field => $ss_priority,
3090 Value => $new_value,
3094 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3095 Field => $ss_priority,
3096 Value => $old_value,
3100 $ticket_error{$id} = $msg if !$val;
3101 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3103 return { 'error' => '',
3104 'ticket_error' => \%ticket_error,
3105 %{ customer_info($p) } # send updated customer info back
3111 sub _custoragent_session_custnum {
3114 my($context, $session, $custnum);
3115 if ( $p->{'session_id'} ) {
3117 $context = 'customer';
3118 $session = _cache->get($p->{'session_id'})
3119 or return ( 'error' => "Can't resume session" ); #better error message
3120 $custnum = $session->{'custnum'};
3122 } elsif ( $p->{'agent_session_id'} ) {
3125 my $agent_cache = new FS::ClientAPI_SessionCache( {
3126 'namespace' => 'FS::ClientAPI::Agent',
3128 $session = $agent_cache->get($p->{'agent_session_id'})
3129 or return ( 'error' => "Can't resume session" ); #better error message
3130 $custnum = $p->{'custnum'};
3134 return ( 'error' => "Can't resume session" ); #better error message
3137 ($context, $session, $custnum);