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 );
8 use Digest::MD5 qw(md5_hex);
10 use Business::CreditCard;
12 use Time::Local qw(timelocal_nocheck);
13 use FS::UI::Web::small_custview qw(small_custview); #less doh
15 use FS::UI::bytecount qw( display_bytecount );
18 use FS::Record qw(qsearch qsearchs dbh);
19 use FS::Msgcat qw(gettext);
20 use FS::Misc qw(card_types);
21 use FS::Misc::DateTime qw(parse_datetime);
22 use FS::ClientAPI_SessionCache;
31 use FS::cust_main_county;
34 use FS::acct_rt_transaction;
39 use Spreadsheet::WriteExcel;
42 $me = '[FS::ClientAPI::MyAccount]';
44 use vars qw( @cust_main_editable_fields );
45 @cust_main_editable_fields = qw(
46 first last company address1 address2 city
47 county state zip country daytime night fax
48 ship_first ship_last ship_company ship_address1 ship_address2 ship_city
49 ship_state ship_zip ship_country ship_daytime ship_night ship_fax
50 payby payinfo payname paystart_month paystart_year payissue payip
51 ss paytype paystate stateid stateid_state
55 $cache ||= new FS::ClientAPI_SessionCache( {
56 'namespace' => 'FS::ClientAPI::MyAccount',
63 my($context, $session, $custnum) = _custoragent_session_custnum($p);
64 #return { 'error' => $session } if $context eq 'error';
67 if ( $context eq 'customer' ) {
69 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
72 $sth->execute($custnum) or die $sth->errstr;
74 $agentnum = $sth->fetchrow_arrayref->[0]
75 or die "no agentnum for custnum $custnum";
77 #} elsif ( $context eq 'agent' ) {
78 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
82 my $conf = new FS::Conf;
84 #false laziness w/Signup.pm
86 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
88 if ( $skin_info_cache_agent ) {
90 warn "$me loading cached skin info for agentnum $agentnum\n"
95 warn "$me populating skin info cache for agentnum $agentnum\n"
98 $skin_info_cache_agent = {
99 'agentnum' => $agentnum,
100 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
101 qw( company_name date_format ) ),
102 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
103 qw( body_bgcolor box_bgcolor
104 text_color link_color vlink_color hlink_color alink_color
105 font title_color title_align title_size menu_bgcolor menu_fontsize
108 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
109 qw( menu_skipblanks menu_skipheadings menu_nounderline )
111 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
112 qw( title_left_image title_right_image
113 menu_top_image menu_body_image menu_bottom_image
116 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
117 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
118 qw( head body_header body_footer company_address ) ),
121 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
125 #{ %$skin_info_cache_agent };
126 $skin_info_cache_agent;
133 my $conf = new FS::Conf;
137 'phone_login' => $conf->exists('selfservice_server-phone_login'),
138 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
145 #false laziness w/FS::ClientAPI::passwd::passwd
149 my $conf = new FS::Conf;
152 if ( $p->{'domain'} eq 'svc_phone'
153 && $conf->exists('selfservice_server-phone_login') ) {
155 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
156 return { error => 'Number not found.' } unless $svc_phone;
159 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
160 #return { error => 'Only primary user may log in.' }
161 # if $conf->exists('selfservice_server-primary_only')
162 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
164 return { error => 'Incorrect PIN.' }
165 unless $svc_phone->check_pin($p->{'password'});
171 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
172 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
174 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
175 'domsvc' => $svc_domain->svcnum, }
177 return { error => 'User not found.' } unless $svc_acct;
179 if($conf->exists('selfservice_server-login_svcpart')) {
180 my @svcpart = $conf->config('selfservice_server-login_svcpart');
181 my $svcpart = $svc_acct->cust_svc->svcpart;
182 return { error => 'Invalid user.' }
183 unless grep($_ eq $svcpart, @svcpart);
186 return { error => 'Incorrect password.' }
187 unless $svc_acct->check_password($p->{'password'});
194 'svcnum' => $svc_x->svcnum,
197 my $cust_svc = $svc_x->cust_svc;
198 my $cust_pkg = $cust_svc->cust_pkg;
200 my $cust_main = $cust_pkg->cust_main;
201 $session->{'custnum'} = $cust_main->custnum;
202 if ( $conf->exists('pkg-balances') ) {
203 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
204 $cust_main->ncancelled_pkgs;
205 $session->{'pkgnum'} = $cust_pkg->pkgnum
206 if scalar(@cust_pkg) > 1;
210 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
211 #return { error => 'Only primary user may log in.' }
212 # if $conf->exists('selfservice_server-primary_only')
213 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
214 my $part_pkg = $cust_pkg->part_pkg;
215 return { error => 'Only primary user may log in.' }
216 if $conf->exists('selfservice_server-primary_only')
217 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
221 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
222 } until ( ! defined _cache->get($session_id) ); #just in case
224 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
225 _cache->set( $session_id, $session, $timeout );
227 return { 'error' => '',
228 'session_id' => $session_id,
234 if ( $p->{'session_id'} ) {
235 _cache->remove($p->{'session_id'});
236 return { %{ skin_info($p) }, 'error' => '' };
238 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
242 sub payment_gateway {
244 # takes a cust_main and a cust_payby entry, returns the payment_gateway
245 my $conf = new FS::Conf;
246 my $cust_main = shift;
247 my $cust_payby = shift;
248 my $gatewaynum = $conf->config('selfservice-payment_gateway');
250 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
251 die "configured gatewaynum $gatewaynum not found!" if !$pg;
255 return '' if ! FS::payby->realtime($cust_payby);
256 my $pg = $cust_main->agent->payment_gateway(
257 'method' => FS::payby->payby2bop($cust_payby),
267 my $conf = new FS::Conf;
269 my $info = skin_info($p);
271 use vars qw( $cust_paybys ); #cache for performance
272 unless ( $cust_paybys ) {
274 my %cust_paybys = map { $_ => 1 }
275 map { FS::payby->payby2payment($_) }
276 $conf->config('signup_server-payby');
278 $cust_paybys = [ keys %cust_paybys ];
281 $info->{'cust_paybys'} = $cust_paybys;
283 my($context, $session, $custnum) = _custoragent_session_custnum($p);
284 return { 'error' => $session } if $context eq 'error';
286 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
287 or return { 'error' => "unknown custnum $custnum" };
289 $info->{'hide_payment_fields'} = [
291 my $pg = payment_gateway($cust_main, $_);
292 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
293 } @{ $info->{cust_paybys} }
296 $info->{'self_suspend_reason'} =
297 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
299 $info->{'edit_ticket_subject'} =
300 $conf->exists('ticket_system-selfservice_edit_subject') &&
301 $cust_main->edit_subject;
304 'custnum' => $custnum,
305 'access_pkgnum' => $session->{'pkgnum'},
306 'access_svcnum' => $session->{'svcnum'},
313 my($context, $session, $custnum) = _custoragent_session_custnum($p);
314 return { 'error' => $session } if $context eq 'error';
318 my $conf = new FS::Conf;
319 if ($conf->exists('cust_main-require_address2')) {
320 $return{'require_address2'} = '1';
322 $return{'require_address2'} = '';
325 if ( $FS::TicketSystem::system ) {
326 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
327 FS::TicketSystem->init();
330 if ( $custnum ) { #customer record
332 my $search = { 'custnum' => $custnum };
333 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
334 my $cust_main = qsearchs('cust_main', $search )
335 or return { 'error' => "unknown custnum $custnum" };
337 if ( $session->{'pkgnum'} ) {
338 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
340 $return{balance} = $cust_main->balance;
343 my @tickets = $cust_main->tickets;
344 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
345 if ( FS::TicketSystem->selfservice_priority ) {
346 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
350 ($a->{'_selfservice_priority'} eq '') <=>
351 ($b->{'_selfservice_priority'} eq '')
354 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
360 $return{tickets} = \@tickets;
363 unless ( $session->{'pkgnum'} ) {
366 invnum => $_->invnum,
367 date => time2str("%b %o, %Y", $_->_date),
370 } $cust_main->open_cust_bill;
371 $return{open_invoices} = \@open;
374 $return{small_custview} =
375 small_custview( $cust_main,
376 scalar($conf->config('countrydefault')),
377 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
380 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
382 for (@cust_main_editable_fields) {
383 $return{$_} = $cust_main->get($_);
386 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
387 $return{payinfo} = $cust_main->paymask;
388 @return{'month', 'year'} = $cust_main->paydate_monthyear;
391 $return{'invoicing_list'} =
392 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
393 $return{'postal_invoicing'} =
394 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
396 if (scalar($conf->config('support_packages'))) {
397 my @support_services = ();
398 foreach ($cust_main->support_services) {
399 my $seconds = $_->svc_x->seconds;
400 my $time_remaining = (($seconds < 0) ? '-' : '' ).
401 int(abs($seconds)/3600)."h".
402 sprintf("%02d",(abs($seconds)%3600)/60)."m";
403 my $cust_pkg = $_->cust_pkg;
406 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
407 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
408 push @support_services, { svcnum => $_->svcnum,
409 time => $time_remaining,
414 $return{support_services} = \@support_services;
417 if ( $conf->config('prepayment_discounts-credit_type') ) {
419 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
422 if ( $session->{'svcnum'} ) {
423 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
424 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
427 } elsif ( $session->{'svcnum'} ) { #no customer record
429 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
430 or die "unknown svcnum";
431 $return{name} = $svc_acct->email;
435 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
439 return { 'error' => '',
440 'custnum' => $custnum,
448 my $session = _cache->get($p->{'session_id'})
449 or return { 'error' => "Can't resume session" }; #better error message
451 my $custnum = $session->{'custnum'}
452 or return { 'error' => "no customer record" };
454 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
455 or return { 'error' => "unknown custnum $custnum" };
457 my $new = new FS::cust_main { $cust_main->hash };
458 $new->set( $_ => $p->{$_} )
459 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
462 if (exists($p->{'payby'})) {
463 $p->{'payby'} =~ /^([A-Z]{4})$/
464 or return { 'error' => "illegal_payby " . $p->{'payby'} };
468 if ( $payby =~ /^(CARD|DCRD)$/ ) {
470 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
472 if ( $new->payinfo eq $cust_main->paymask ) {
473 $new->payinfo($cust_main->payinfo);
475 $new->payinfo($p->{'payinfo'});
478 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
480 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
483 $p->{'payinfo1'} =~ /^([\dx]+)$/
484 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
486 $p->{'payinfo2'} =~ /^([\dx]+)$/
487 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
489 $payinfo = $payinfo1. '@'. $payinfo2;
491 $new->payinfo( ($payinfo eq $cust_main->paymask)
492 ? $cust_main->payinfo
496 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
498 } elsif ( $payby =~ /^(BILL)$/ ) {
500 } elsif ( $payby ) { #notyet ready
501 return { 'error' => "unknown payby $payby" };
505 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
506 #false laziness with httemplate/edit/process/cust_main.cgi
507 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
508 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
510 @invoicing_list = $cust_main->invoicing_list;
513 my $error = $new->replace($cust_main, \@invoicing_list);
514 return { 'error' => $error } if $error;
517 return { 'error' => '' };
522 my $session = _cache->get($p->{'session_id'})
523 or return { 'error' => "Can't resume session" }; #better error message
529 my $conf = new FS::Conf;
530 use vars qw($payment_info); #cache for performance
531 unless ( $payment_info ) {
533 my %states = map { $_->state => 1 }
534 qsearch('cust_main_county', {
535 'country' => $conf->config('countrydefault') || 'US'
538 my %cust_paybys = map { $_ => 1 }
539 map { FS::payby->payby2payment($_) }
540 $conf->config('signup_server-payby');
542 my @cust_paybys = keys %cust_paybys;
546 #list all counties/states/countries
547 'cust_main_county' =>
548 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
550 #shortcut for one-country folks
552 [ sort { $a cmp $b } keys %states ],
554 'card_types' => card_types(),
556 'paytypes' => [ @FS::cust_main::paytypes ],
558 'paybys' => [ $conf->config('signup_server-payby') ],
559 'cust_paybys' => \@cust_paybys,
561 'stateid_label' => FS::Msgcat::_gettext('stateid'),
562 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
564 'show_ss' => $conf->exists('show_ss'),
565 'show_stateid' => $conf->exists('show_stateid'),
566 'show_paystate' => $conf->exists('show_bankstate'),
568 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
570 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
579 my %return = %$payment_info;
581 my $custnum = $session->{'custnum'};
583 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
584 or return { 'error' => "unknown custnum $custnum" };
586 $return{'hide_payment_fields'} = [
588 my $pg = payment_gateway($cust_main, $_);
589 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
590 } @{ $return{cust_paybys} }
593 $return{balance} = $cust_main->balance; #XXX pkg-balances?
595 $return{payname} = $cust_main->payname
596 || ( $cust_main->first. ' '. $cust_main->get('last') );
598 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
600 $return{payby} = $cust_main->payby;
601 $return{stateid_state} = $cust_main->stateid_state;
603 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
604 $return{card_type} = cardtype($cust_main->payinfo);
605 $return{payinfo} = $cust_main->paymask;
607 @return{'month', 'year'} = $cust_main->paydate_monthyear;
611 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
612 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
613 $return{payinfo1} = $payinfo1;
614 $return{payinfo2} = $payinfo2;
615 $return{paytype} = $cust_main->paytype;
616 $return{paystate} = $cust_main->paystate;
620 if ( $conf->config('prepayment_discounts-credit_type') ) {
622 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
625 #doubleclick protection
627 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
629 return { 'error' => '',
635 #some false laziness with httemplate/process/payment.cgi - look there for
636 #ACH and CVV support stuff
638 sub validate_payment {
641 my $session = _cache->get($p->{'session_id'})
642 or return { 'error' => "Can't resume session" }; #better error message
644 my $custnum = $session->{'custnum'};
646 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
647 or return { 'error' => "unknown custnum $custnum" };
649 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
650 or return { 'error' => gettext('illegal_amount') };
652 return { error => 'Amount must be greater than 0' } unless $amount > 0;
654 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
655 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
656 my $discount_term = $1;
658 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
659 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
662 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
663 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
666 $p->{'payby'} ||= 'CARD';
667 $p->{'payby'} =~ /^([A-Z]{4})$/
668 or return { 'error' => "illegal_payby " . $p->{'payby'} };
671 #false laziness w/process/payment.cgi
674 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
676 $p->{'payinfo1'} =~ /^([\dx]+)$/
677 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
679 $p->{'payinfo2'} =~ /^([\dx]+)$/
680 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
682 $payinfo = $payinfo1. '@'. $payinfo2;
684 $payinfo = $cust_main->payinfo
685 if $cust_main->paymask eq $payinfo;
687 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
689 $payinfo = $p->{'payinfo'};
691 #more intelligent mathing will be needed here if you change
692 #card_masking_method and don't remove existing paymasks
693 $payinfo = $cust_main->payinfo
694 if $cust_main->paymask eq $payinfo;
697 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
698 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
702 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
703 return { 'error' => gettext('unknown_card_type') }
704 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
706 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
707 if ( cardtype($payinfo) eq 'American Express card' ) {
708 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
709 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
712 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
713 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
719 die "unknown payby $payby";
723 'CARD' => [ qw( paystart_month paystart_year payissue payip
724 address1 address2 city state zip country ) ],
725 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
729 $card_type = cardtype($payinfo) if $payby eq 'CARD';
732 'cust_main' => $cust_main, #XXX or just custnum??
735 'payinfo' => $payinfo,
736 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
737 'card_type' => $card_type,
738 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
739 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
740 'payname' => $payname,
741 'paybatch' => $paybatch, #this doesn't actually do anything
743 'payname' => $payname,
744 'discount_term' => $discount_term,
745 'pkgnum' => $session->{'pkgnum'},
746 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
756 my $validate = validate_payment($p);
757 return $validate if $validate->{'error'};
759 my $conf = new FS::Conf;
760 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
761 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
763 +{ map { $_=>$validate->{$_} }
764 qw( card_type paymask payname paydate_pretty amount )
769 sub process_stored_payment {
772 my $session_id = $p->{'session_id'};
774 my $payment_info = _cache->get( "payment_$session_id" )
775 or return { 'error' => "Can't resume session" }; #better error message
777 do_process_payment($payment_info);
781 sub process_payment {
784 my $payment_info = validate_payment($p);
785 return $payment_info if $payment_info->{'error'};
787 do_process_payment($payment_info);
791 sub do_process_payment {
792 my $validate = shift;
794 my $cust_main = $validate->{'cust_main'};
796 my $amount = delete $validate->{'amount'};
799 my $payby = delete $validate->{'payby'};
801 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
804 'fake' => 1, #XXX DO NOT CHECK ME IN
805 'paynum_ref' => \$paynum,
808 return { 'error' => $error } if $error;
810 $cust_main->apply_payments;
812 if ( $validate->{'save'} ) {
813 my $new = new FS::cust_main { $cust_main->hash };
814 if ($validate->{'payby'} eq 'CARD' || $validate->{'payby'} eq 'DCRD') {
815 $new->set( $_ => $validate->{$_} )
816 foreach qw( payname paystart_month paystart_year payissue payip
817 address1 address2 city state zip country );
818 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
819 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
820 $new->set( $_ => $validate->{$_} )
821 foreach qw( payname payip paytype paystate
822 stateid stateid_state );
823 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
825 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
826 $new->set( 'paydate' => $validate->{'paydate'} );
827 my $error = $new->replace($cust_main);
829 #no, this causes customers to process their payments again
830 #return { 'error' => $error };
831 #XXX just warn verosely for now so i can figure out how these happen in
832 # the first place, eventually should redirect them to the "change
833 #address" page but indicate the payment did process??
834 delete($validate->{'payinfo'}); #don't want to log this!
835 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
836 "NEW: ". Dumper($new)."\n".
837 "OLD: ". Dumper($cust_main)."\n".
838 "PACKET: ". Dumper($validate)."\n";
846 my $receipt_html = '';
848 # currently supported for realtime CC only; send receipt data to SS
849 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
852 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
855 <TD ALIGN="right">Payment#</TD>
856 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
860 <TD ALIGN="right">Date</TD>
862 <TD BGCOLOR="#FFFFFF"><B>! .
863 time2str("%a %b %o, %Y %r", $cust_pay->_date)
869 <TD ALIGN="right">Amount</TD>
870 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
875 <TD ALIGN="right">Payment method</TD>
876 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
887 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
891 'amount' => sprintf('%.2f', $cust_pay->paid),
892 'date' => $cust_pay->_date,
893 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
894 'time_pretty' => time2str('%T', $cust_pay->_date),
896 'order_num' => $order,
897 'receipt_html' => $receipt_html,
904 'receipt_html' => '',
911 sub realtime_collect {
914 my $session = _cache->get($p->{'session_id'})
915 or return { 'error' => "Can't resume session" }; #better error message
917 my $custnum = $session->{'custnum'};
919 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
920 or return { 'error' => "unknown custnum $custnum" };
923 if ( $p->{'amount'} ) {
924 $amount = $p->{'amount'};
926 elsif ( $session->{'pkgnum'} ) {
927 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
930 $amount = $cust_main->balance;
933 my $error = $cust_main->realtime_collect(
934 'method' => $p->{'method'},
936 'pkgnum' => $session->{'pkgnum'},
937 'session_id' => $p->{'session_id'},
941 return { 'error' => $error } unless ref( $error );
943 return { 'error' => '', amount => $amount, %$error };
946 sub process_payment_order_pkg {
949 my $hr = process_payment($p);
950 return $hr if $hr->{'error'};
955 sub process_payment_order_renew {
958 my $hr = process_payment($p);
959 return $hr if $hr->{'error'};
968 my $session = _cache->get($p->{'session_id'})
969 or return { 'error' => "Can't resume session" }; #better error message
973 my $custnum = $session->{'custnum'};
975 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
976 or return { 'error' => "unknown custnum $custnum" };
978 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
979 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
987 return { 'error' => $error } if $error;
989 return { 'error' => '',
991 'seconds' => $seconds,
992 'duration' => duration_exact($seconds),
993 'upbytes' => $upbytes,
994 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
995 'downbytes' => $downbytes,
996 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
997 'totalbytes'=> $totalbytes,
998 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1005 my $session = _cache->get($p->{'session_id'})
1006 or return { 'error' => "Can't resume session" }; #better error message
1008 my $custnum = $session->{'custnum'};
1010 my $invnum = $p->{'invnum'};
1012 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1013 'custnum' => $custnum } )
1014 or return { 'error' => "Can't find invnum" };
1018 return { 'error' => '',
1019 'invnum' => $invnum,
1020 'invoice_text' => join('', $cust_bill->print_text ),
1021 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1028 my $session = _cache->get($p->{'session_id'})
1029 or return { 'error' => "Can't resume session" }; #better error message
1031 my $custnum = $session->{'custnum'};
1033 my $invnum = $p->{'invnum'};
1035 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1036 'custnum' => $custnum } )
1037 or return { 'error' => "Can't find invnum" };
1041 return { 'error' => '',
1042 'invnum' => $invnum,
1043 'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
1051 #sessioning for this? how do we get the session id to the backend invoice
1052 # template so it can add it to the link, blah
1055 if ( $p->{'invnum'} ) {
1056 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1057 or return { 'error' => 'unknown invnum' };
1058 $agentnum = $cust_bill->cust_main->agentnum;
1061 my $templatename = $p->{'template'} || $p->{'templatename'};
1063 #false laziness-ish w/view/cust_bill-logo.cgi
1065 my $conf = new FS::Conf;
1066 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1067 $templatename = "_$1";
1072 my $filename = "logo$templatename.png";
1074 return { 'error' => '',
1075 'logo' => $conf->config_binary($filename, $agentnum),
1076 'content_type' => 'image/png', #should allow gif, jpg too
1083 my $session = _cache->get($p->{'session_id'})
1084 or return { 'error' => "Can't resume session" }; #better error message
1086 my $custnum = $session->{'custnum'};
1088 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1089 or return { 'error' => "unknown custnum $custnum" };
1091 my @cust_bill = $cust_main->cust_bill;
1095 return { 'error' => '',
1096 'balance' => $cust_main->balance,
1099 my $owed = $_->owed;
1101 +{ 'invnum' => $_->invnum,
1102 '_date' => $_->_date,
1103 'date' => time2str("%b %o, %Y", $_->_date),
1104 'date_short' => time2str("%m-%d-%Y", $_->_date),
1105 'previous' => sprintf('%.2f', ($_->previous)[0]),
1106 'charged' => sprintf('%.2f', $_->charged),
1107 'owed' => sprintf('%.2f', $owed),
1108 'balance' => sprintf('%.2f', $balance),
1118 my $session = _cache->get($p->{'session_id'})
1119 or return { 'error' => "Can't resume session" }; #better error message
1121 my $custnum = $session->{'custnum'};
1123 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1124 or return { 'error' => "unknown custnum $custnum" };
1126 my @errors = $cust_main->cancel( 'quiet'=>1 );
1128 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1130 return { 'error' => $error };
1137 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1138 return { 'error' => $session } if $context eq 'error';
1140 my $search = { 'custnum' => $custnum };
1141 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1142 my $cust_main = qsearchs('cust_main', $search )
1143 or return { 'error' => "unknown custnum $custnum" };
1145 my $conf = new FS::Conf;
1147 # the duplication below is necessary:
1148 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1149 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1150 # non-backwards-compatible change breaking the software of anyone using the API
1151 # instead of the stock selfservice
1152 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1153 if( $conf->exists('selfservice_server-view-wholesale') ) {
1154 return { 'svcnum' => $session->{'svcnum'},
1155 'custnum' => $custnum,
1156 'cust_pkg' => [ map {
1158 part_pkg => [ map $_->hashref, $_->part_pkg ],
1160 [ map $_->hashref, $_->available_part_svc ],
1162 [ map { my $ref = { $_->hash,
1163 label => [ $_->label ],
1165 $ref->{_password} = $_->svc_x->_password
1166 if $context eq 'agent'
1167 && $conf->exists('agent-showpasswords')
1168 && $_->part_svc->svcdb eq 'svc_acct';
1173 } $cust_main->cust_pkg
1176 small_custview( $cust_main, $conf->config('countrydefault') ),
1177 'wholesale_view' => 1,
1178 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1179 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1180 'lnp' => $conf->exists('svc_phone-lnp'),
1184 { 'svcnum' => $session->{'svcnum'},
1185 'custnum' => $custnum,
1186 'cust_pkg' => [ map {
1187 my $primary_cust_svc = $_->primary_cust_svc;
1190 status => $_->status,
1192 [ map $_->hashref, $_->available_part_svc ],
1194 [ map { my $ref = { $_->hash,
1195 label => [ $_->label ],
1197 $ref->{_password} = $_->svc_x->_password
1198 if $context eq 'agent'
1199 && $conf->exists('agent-showpasswords')
1200 && $_->part_svc->svcdb eq 'svc_acct';
1201 $ref->{svchash} = { $_->svc_x->hash } if
1202 $_->part_svc->svcdb eq 'svc_phone';
1203 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1204 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1210 ? { $primary_cust_svc->hash,
1211 label => [ $primary_cust_svc->label ],
1212 finger => $primary_cust_svc->svc_x->finger, #uuh
1213 $primary_cust_svc->part_svc->hash,
1217 } $cust_main->ncancelled_pkgs
1220 small_custview( $cust_main, $conf->config('countrydefault') ),
1228 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1229 return { 'error' => $session } if $context eq 'error';
1231 my $search = { 'custnum' => $custnum };
1232 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1233 my $cust_main = qsearchs('cust_main', $search )
1234 or return { 'error' => "unknown custnum $custnum" };
1237 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1238 foreach my $cust_pkg ( $p->{'ncancelled'}
1239 ? $cust_main->ncancelled_pkgs
1240 : $cust_main->unsuspended_pkgs ) {
1241 next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1242 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1244 if ( $p->{'svcdb'} ) {
1245 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1247 : ref($p->{'svcdb'}) eq 'ARRAY'
1248 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1249 : { $p->{'svcdb'} => 1 };
1250 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1253 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1256 my $conf = new FS::Conf;
1259 'svcnum' => $session->{'svcnum'},
1260 'custnum' => $custnum,
1261 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1262 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1265 my $svc_x = $_->svc_x;
1266 my($label, $value) = $_->label;
1267 my $svcdb = $_->part_svc->svcdb;
1268 my $part_pkg = $_->cust_pkg->part_pkg;
1271 'svcnum' => $_->svcnum,
1277 if ( $svcdb eq 'svc_acct' ) {
1280 'username' => $svc_x->username,
1281 'email' => $svc_x->email,
1282 'seconds' => $svc_x->seconds,
1283 'upbytes' => display_bytecount($svc_x->upbytes),
1284 'downbytes' => display_bytecount($svc_x->downbytes),
1285 'totalbytes' => display_bytecount($svc_x->totalbytes),
1287 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1288 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1289 'recharge_upbytes' =>
1290 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1291 'recharge_downbytes' =>
1292 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1293 'recharge_totalbytes' =>
1294 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1298 } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1314 _usage_details( \&_port_graph, $p,
1315 'svcdb' => 'svc_port',
1320 my($svc_port, $begin, $end) = @_;
1322 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1323 push @usage, { 'png' => $pngOrError };
1327 sub _list_svc_usage {
1328 my($svc_acct, $begin, $end) = @_;
1330 foreach my $part_export (
1331 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1332 qw( sqlradius sqlradius_withdomain )
1334 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1339 sub list_svc_usage {
1340 _usage_details(\&_list_svc_usage, @_);
1343 sub _list_support_usage {
1344 my($svc_acct, $begin, $end) = @_;
1346 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1347 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1349 push @usage, { 'seconds' => $_->seconds,
1350 'support' => $_->support,
1351 '_date' => $_->_date,
1352 'id' => $_->transaction_id,
1353 'creator' => $_->creator,
1354 'subject' => $_->subject,
1355 'status' => $_->status,
1356 'ticketid' => $_->ticketid,
1362 sub list_support_usage {
1363 _usage_details(\&_list_support_usage, @_);
1366 sub _list_cdr_usage {
1367 my($svc_phone, $begin, $end) = @_;
1368 map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1369 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1372 sub list_cdr_usage {
1374 _usage_details( \&_list_cdr_usage, $p,
1375 'svcdb' => 'svc_phone',
1379 sub _usage_details {
1380 my($callback, $p, %opt) = @_;
1382 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1383 return { 'error' => $session } if $context eq 'error';
1385 my $search = { 'svcnum' => $p->{'svcnum'} };
1386 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1388 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1390 my $svc_x = qsearchs( $svcdb, $search );
1391 return { 'error' => 'No service selected in list_svc_usage' }
1394 my $header = $svcdb eq 'svc_phone'
1395 ? [ split(',', FS::cdr::invoice_header('default') ) ] #XXX
1398 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1399 my $freq = $cust_pkg->part_pkg->freq;
1400 my $start = $cust_pkg->setup;
1401 #my $end = $cust_pkg->bill; # or time?
1404 unless ( $p->{beginning} ) {
1405 $p->{beginning} = $cust_pkg->last_bill;
1406 $p->{ending} = $end;
1409 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1411 #kinda false laziness with FS::cust_main::bill, but perhaps
1412 #we should really change this bit to DateTime and DateTime::Duration
1414 #change this bit to use Date::Manip? CAREFUL with timezones (see
1415 # mailing list archive)
1416 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1417 (localtime($p->{ending}) )[0,1,2,3,4,5];
1418 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1419 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1421 if ( $freq =~ /^\d+$/ ) {
1423 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1425 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1426 } elsif ( $freq =~ /^(\d+)w$/ ) {
1428 $nmday += $weeks * 7;
1429 $pmday -= $weeks * 7;
1430 } elsif ( $freq =~ /^(\d+)d$/ ) {
1434 } elsif ( $freq =~ /^(\d+)h$/ ) {
1439 return { 'error' => "unparsable frequency: ". $freq };
1442 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1443 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1447 'svcnum' => $p->{svcnum},
1448 'beginning' => $p->{beginning},
1449 'ending' => $p->{ending},
1450 'previous' => ($previous > $start) ? $previous : $start,
1451 'next' => ($next < $end) ? $next : $end,
1452 'header' => $header,
1460 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1461 return { 'error' => $session } if $context eq 'error';
1463 my $search = { 'custnum' => $custnum };
1464 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1465 my $cust_main = qsearchs('cust_main', $search )
1466 or return { 'error' => "unknown custnum $custnum" };
1468 my $status = $cust_main->status;
1469 #false laziness w/ClientAPI/Signup.pm
1471 my $cust_pkg = new FS::cust_pkg ( {
1472 'custnum' => $custnum,
1473 'pkgpart' => $p->{'pkgpart'},
1475 my $error = $cust_pkg->check;
1476 return { 'error' => $error } if $error;
1479 unless ( $p->{'svcpart'} eq 'none' ) {
1483 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1485 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1486 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1487 $svcdb = $part_svc->svcdb;
1489 $svcdb = 'svc_acct';
1491 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1494 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
1495 'svc_domain' => [ qw( domain ) ],
1496 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
1497 'svc_external' => [ qw( id title ) ],
1498 'svc_pbx' => [ qw( id title ) ],
1501 my $svc_x = "FS::$svcdb"->new( {
1502 'svcpart' => $svcpart,
1503 map { $_ => $p->{$_} } @{$fields{$svcdb}}
1506 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1509 while ( length($p->{"snarf_machine$snarfnum"}) ) {
1510 my $acct_snarf = new FS::acct_snarf ( {
1511 'machine' => $p->{"snarf_machine$snarfnum"},
1512 'protocol' => $p->{"snarf_protocol$snarfnum"},
1513 'username' => $p->{"snarf_username$snarfnum"},
1514 '_password' => $p->{"snarf_password$snarfnum"},
1517 push @acct_snarf, $acct_snarf;
1519 $svc_x->child_objects( \@acct_snarf );
1522 my $y = $svc_x->setdefault; # arguably should be in new method
1523 return { 'error' => $y } if $y && !ref($y);
1525 $error = $svc_x->check;
1526 return { 'error' => $error } if $error;
1533 tie my %hash, 'Tie::RefHash';
1534 %hash = ( $cust_pkg => \@svc );
1536 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1537 return { 'error' => $error } if $error;
1539 my $conf = new FS::Conf;
1540 if ( $conf->exists('signup_server-realtime') ) {
1542 my $bill_error = _do_bop_realtime( $cust_main, $status );
1545 $cust_pkg->cancel('quiet'=>1);
1548 $cust_pkg->reexport;
1552 $cust_pkg->reexport;
1555 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1557 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1564 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1565 return { 'error' => $session } if $context eq 'error';
1567 my $search = { 'custnum' => $custnum };
1568 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1569 my $cust_main = qsearchs('cust_main', $search )
1570 or return { 'error' => "unknown custnum $custnum" };
1572 my $status = $cust_main->status;
1573 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1574 or return { 'error' => "unknown package $p->{pkgnum}" };
1577 my $error = FS::cust_pkg::order( $custnum,
1583 my $conf = new FS::Conf;
1584 if ( $conf->exists('signup_server-realtime') ) {
1586 my $bill_error = _do_bop_realtime( $cust_main, $status );
1589 $newpkg[0]->suspend;
1592 $newpkg[0]->reexport;
1596 $newpkg[0]->reexport;
1599 return { error => '', pkgnum => $cust_pkg->pkgnum };
1603 sub order_recharge {
1606 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1607 return { 'error' => $session } if $context eq 'error';
1609 my $search = { 'custnum' => $custnum };
1610 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1611 my $cust_main = qsearchs('cust_main', $search )
1612 or return { 'error' => "unknown custnum $custnum" };
1614 my $status = $cust_main->status;
1615 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1616 or return { 'error' => "unknown service " . $p->{'svcnum'} };
1618 my $svc_x = $cust_svc->svc_x;
1619 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1622 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
1623 qw ( recharge_seconds recharge_upbytes recharge_downbytes
1624 recharge_totalbytes );
1625 my $amount = $part_pkg->option('recharge_amount', 1);
1627 my ($l, $v, $d) = $cust_svc->label; # blah
1628 my $pkg = "Recharge $v";
1630 my $bill_error = $cust_main->charge($amount, $pkg,
1631 "time: $vhash{seconds}, up: $vhash{upbytes}," .
1632 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1633 $part_pkg->taxclass); #meh
1635 my $conf = new FS::Conf;
1636 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1638 $bill_error = _do_bop_realtime( $cust_main, $status );
1643 my $error = $svc_x->recharge (\%vhash);
1644 return { 'error' => $error } if $error;
1648 my $error = $bill_error;
1649 $error ||= $svc_x->recharge (\%vhash);
1650 return { 'error' => $error } if $error;
1653 return { error => '', svc => $cust_svc->part_svc->svc };
1657 sub _do_bop_realtime {
1658 my ($cust_main, $status) = (shift, shift);
1660 my $old_balance = $cust_main->balance;
1662 my $bill_error = $cust_main->bill
1663 || $cust_main->apply_payments_and_credits
1664 || $cust_main->realtime_collect('selfservice' => 1);
1666 if ( $cust_main->balance > $old_balance
1667 && $cust_main->balance > 0
1668 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1669 1 : $status eq 'suspended' ) ) {
1670 #this makes sense. credit is "un-doing" the invoice
1671 my $conf = new FS::Conf;
1672 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1673 'self-service decline',
1674 'reason_type' => $conf->config('signup_credit_type'),
1676 $cust_main->apply_credits( 'order' => 'newest' );
1678 return { 'error' => '_decline', 'bill_error' => $bill_error };
1687 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1688 return { 'error' => $session } if $context eq 'error';
1690 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1691 or return { 'error' => "unknown custnum $custnum" };
1693 my @cust_pkg = sort { $a->bill <=> $b->bill }
1694 grep { $_->part_pkg->freq ne '0' }
1695 $cust_main->ncancelled_pkgs;
1697 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1699 my $total = $cust_main->balance;
1702 my $bill = $_->bill;
1703 $total += $_->part_pkg->base_recur($_, \$bill);
1704 my $renew_date = $_->part_pkg->add_freq($_->bill);
1706 'pkgnum' => $_->pkgnum,
1707 'amount' => sprintf('%.2f', $total),
1708 'bill_date' => $_->bill,
1709 'bill_date_pretty' => time2str('%x', $_->bill),
1710 'renew_date' => $renew_date,
1711 'renew_date_pretty' => time2str('%x', $renew_date),
1712 'expire_date' => $_->expire,
1713 'expire_date_pretty' => time2str('%x', $_->expire),
1718 return { 'dates' => \@array };
1722 sub payment_info_renew_info {
1724 my $renew_info = renew_info($p);
1725 my $payment_info = payment_info($p);
1726 return { %$renew_info,
1734 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1735 return { 'error' => $session } if $context eq 'error';
1737 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1738 or return { 'error' => "unknown custnum $custnum" };
1740 my $date = $p->{'date'};
1744 #freeside-daily -n -d $date fs_daily $custnum
1745 $cust_main->bill_and_collect( 'time' => $date,
1746 'invoice_time' => $now,
1747 'actual_time' => $now,
1748 'check_freq' => '1d',
1751 return { 'error' => '' };
1757 my $session = _cache->get($p->{'session_id'})
1758 or return { 'error' => "Can't resume session" }; #better error message
1760 my $custnum = $session->{'custnum'};
1762 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1763 or return { 'error' => "unknown custnum $custnum" };
1765 my $conf = new FS::Conf;
1767 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1768 or return { 'error' => 'Permission denied' };
1770 my $pkgnum = $p->{'pkgnum'};
1772 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1773 'pkgnum' => $pkgnum, } )
1774 or return { 'error' => "unknown pkgnum $pkgnum" };
1776 my $error = $cust_pkg->suspend(reason => $reasonnum);
1777 return { 'error' => $error };
1783 my $session = _cache->get($p->{'session_id'})
1784 or return { 'error' => "Can't resume session" }; #better error message
1786 my $custnum = $session->{'custnum'};
1788 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1789 or return { 'error' => "unknown custnum $custnum" };
1791 my $pkgnum = $p->{'pkgnum'};
1793 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1794 'pkgnum' => $pkgnum, } )
1795 or return { 'error' => "unknown pkgnum $pkgnum" };
1797 my $error = $cust_pkg->cancel('quiet' => 1);
1798 return { 'error' => $error };
1802 sub provision_phone {
1805 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1807 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1808 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1809 return { 'error' => $session } if $context eq 'error';
1811 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1812 return { 'error' => 'service not found' } unless $svc_phone;
1813 return { 'error' => 'invalid svcnum' }
1814 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1816 $svc_phone->email($p->{'email'})
1817 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1818 $svc_phone->forwarddst($p->{'forwarddst'})
1819 if $svc_phone->forwarddst ne $p->{'forwarddst'}
1820 && $p->{'forwarddst'} =~ /^(\d+|)$/;
1821 return { 'error' => $svc_phone->replace };
1825 unless($p->{'lnp'}) {
1826 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1827 $p->{'lnp_status'} = "portingin";
1828 return _provision( 'FS::svc_phone',
1829 [qw(lnp_desired_due_date lnp_other_provider
1830 lnp_other_provider_account phonenum countrycode lnp_status)],
1831 [qw(phonenum countrycode)],
1838 unless (scalar(@bulkdid)) {
1839 return _provision( 'FS::svc_phone',
1840 [qw(phonenum countrycode)],
1841 [qw(phonenum countrycode)],
1847 # bulk DID order case
1849 foreach my $did ( @bulkdid ) {
1850 $did =~ s/[^0-9]//g;
1851 $error = _provision( 'FS::svc_phone',
1852 [qw(phonenum countrycode)],
1853 [qw(phonenum countrycode)],
1855 'pkgnum' => $p->{'pkgnum'},
1856 'svcpart' => $p->{'svcpart'},
1858 'countrycode' => $p->{'countrycode'},
1859 'session_id' => $p->{'session_id'},
1862 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1864 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1867 sub provision_acct {
1869 warn "provision_acct called\n"
1872 return { 'error' => gettext('passwords_dont_match') }
1873 if $p->{'_password'} ne $p->{'_password2'};
1874 return { 'error' => gettext('empty_password') }
1875 unless length($p->{'_password'});
1877 if ($p->{'domsvc'}) {
1878 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1879 qw ( svcpart pkgnum ) );
1880 return { 'error' => gettext('invalid_domain') }
1881 unless ($domains{$p->{'domsvc'}});
1884 warn "provision_acct calling _provision\n"
1886 _provision( 'FS::svc_acct',
1887 [qw(username _password domsvc)],
1888 [qw(username _password domsvc)],
1894 sub provision_external {
1896 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1897 _provision( 'FS::svc_external',
1906 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1907 warn "_provision called for $class\n"
1910 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1911 return { 'error' => $session } if $context eq 'error';
1913 my $search = { 'custnum' => $custnum };
1914 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1915 my $cust_main = qsearchs('cust_main', $search )
1916 or return { 'error' => "unknown custnum $custnum" };
1918 my $pkgnum = $p->{'pkgnum'};
1920 warn "searching for custnum $custnum pkgnum $pkgnum\n"
1922 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1923 'pkgnum' => $pkgnum,
1925 or return { 'error' => "unknown pkgnum $pkgnum" };
1927 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1929 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1930 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1932 warn "creating $class record\n"
1934 my $svc_x = $class->new( {
1935 'pkgnum' => $p->{'pkgnum'},
1936 'svcpart' => $p->{'svcpart'},
1937 map { $_ => $p->{$_} } @$fields
1939 warn "inserting $class record\n"
1941 my $error = $svc_x->insert;
1944 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1946 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1949 my $return = { 'svc' => $part_svc->svc,
1951 map { $_ => $svc_x->get($_) } @$return_fields
1953 warn "_provision returning ". Dumper($return). "\n"
1962 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1963 return { 'error' => $session } if $context eq 'error';
1965 my $search = { 'custnum' => $custnum };
1966 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1967 my $cust_main = qsearchs('cust_main', $search )
1968 or return { 'error' => "unknown custnum $custnum" };
1970 my $pkgnum = $p->{'pkgnum'};
1972 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1973 'pkgnum' => $pkgnum,
1975 or return { 'error' => "unknown pkgnum $pkgnum" };
1977 my $svcpart = $p->{'svcpart'};
1979 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1980 'svcpart' => $svcpart, } )
1981 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1982 my $part_svc = $pkg_svc->part_svc;
1984 my $conf = new FS::Conf;
1987 'svc' => $part_svc->svc,
1988 'svcdb' => $part_svc->svcdb,
1989 'pkgnum' => $pkgnum,
1990 'svcpart' => $svcpart,
1991 'custnum' => $custnum,
1993 'security_phrase' => 0, #XXX !
1994 'svc_acct_pop' => [], #XXX !
1996 'init_popstate' => '',
2001 small_custview( $cust_main, $conf->config('countrydefault') ),
2005 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2006 && $ret->{'svcdb'} eq 'svc_phone') {
2007 $ret->{'svcnum'} = $p->{'svcnum'};
2008 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2009 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2010 $ret->{'email'} = $svc_phone->email;
2011 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2018 sub unprovision_svc {
2021 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2022 return { 'error' => $session } if $context eq 'error';
2024 my $search = { 'custnum' => $custnum };
2025 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2026 my $cust_main = qsearchs('cust_main', $search )
2027 or return { 'error' => "unknown custnum $custnum" };
2029 my $svcnum = $p->{'svcnum'};
2031 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2032 or return { 'error' => "unknown svcnum $svcnum" };
2034 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2035 unless $cust_svc->cust_pkg->custnum == $custnum;
2037 my $conf = new FS::Conf;
2039 return { 'svc' => $cust_svc->part_svc->svc,
2040 'error' => $cust_svc->cancel,
2042 small_custview( $cust_main, $conf->config('countrydefault') ),
2047 sub myaccount_passwd {
2049 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2050 return { 'error' => $session } if $context eq 'error';
2052 return { 'error' => "New passwords don't match." }
2053 if $p->{'new_password'} ne $p->{'new_password2'};
2055 return { 'error' => 'Enter new password' }
2056 unless length($p->{'new_password'});
2058 #my $search = { 'custnum' => $custnum };
2059 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2060 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2061 my $search = " AND custnum = $1";
2062 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2064 my $svc_acct = qsearchs( {
2065 'table' => 'svc_acct',
2066 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2067 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2068 'LEFT JOIN cust_main USING ( custnum ) ',
2069 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2070 'extra_sql' => $search, #important
2072 or return { 'error' => "Service not found" };
2074 $svc_acct->_password($p->{'new_password'});
2075 my $error = $svc_acct->replace();
2077 my($label, $value) = $svc_acct->cust_svc->label;
2079 return { 'error' => $error,
2088 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2089 return { 'error' => $session } if $context eq 'error';
2091 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2092 FS::TicketSystem->init();
2094 my $conf = new FS::Conf;
2095 my $queue = $p->{'queue'}
2096 || $conf->config('ticket_system-selfservice_queueid')
2097 || $conf->config('ticket_system-default_queueid');
2099 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2100 my $err_or_ticket = FS::TicketSystem->create_ticket(
2101 '', #create RT session based on FS CurrentUser (fs_selfservice)
2103 'custnum' => $custnum,
2104 'svcnum' => $session->{'svcnum'},
2105 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2108 if ( ref($err_or_ticket) ) {
2109 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2111 return { 'error' => '',
2112 'ticket_id' => $err_or_ticket->id,
2115 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2117 return { 'error' => $err_or_ticket };
2125 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2126 return { 'error' => $session } if $context eq 'error';
2128 return { error => 'requested format not implemented' }
2129 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2131 my $conf = new FS::Conf;
2132 my $age_threshold = 0;
2133 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2134 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2136 my $search = { 'custnum' => $custnum };
2137 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2138 my $cust_main = qsearchs('cust_main', $search )
2139 or return { 'error' => "unknown custnum $custnum" };
2141 # does it make more sense to just run one sql query for this instead of all the
2142 # insanity below? would increase performance greately for large data sets?
2144 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2145 my @part_svc = $cust_pkg->part_svc;
2146 foreach my $part_svc ( @part_svc ) {
2147 if($part_svc->svcdb eq 'svc_phone'){
2148 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2149 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2150 push @svc_phone, $cust_pkg_svc->svc_x
2151 if $cust_pkg_svc->date_inserted >= $age_threshold;
2159 my($xls_r,$xls_c) = (0,0);
2162 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2163 if($p->{'format'} eq 'csv') {
2164 $csv = new Text::CSV_XS { 'always_quote' => 1,
2167 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2168 $content .= $csv->string;
2170 elsif($p->{'format'} eq 'xls') {
2171 my $XLS1 = new IO::Scalar \$content;
2172 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2173 or return { 'error' => "Error opening .xls file: $!" };
2174 $xls = $xls_workbook->add_worksheet('DIDs');
2175 foreach ( @fields ) {
2176 $xls->write(0,$xls_c++,$_);
2181 foreach my $svc_phone ( @svc_phone ) {
2182 my @cols = map { $svc_phone->$_ } @fields;
2183 if($p->{'format'} eq 'csv') {
2184 return { 'error' => 'Unable to create CSV' }
2185 unless $csv->combine(@cols);
2186 $content .= $csv->string;
2188 elsif($p->{'format'} eq 'xls') {
2191 $xls->write($xls_r,$xls_c++,$_);
2197 $xls_workbook->close() if $p->{'format'} eq 'xls';
2199 { content => $content, format => $p->{'format'}, };
2204 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2205 return { 'error' => $session } if $context eq 'error';
2207 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2208 FS::TicketSystem->init();
2209 return { 'error' => 'get_ticket configuration error' }
2210 if $FS::TicketSystem::system ne 'RT_Internal';
2212 # check existence and ownership as part of this
2213 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2214 my $rt_session = FS::TicketSystem->session('');
2215 my $Ticket = FS::TicketSystem->get_ticket_object(
2217 ticket_id => $p->{'ticket_id'},
2220 return { 'error' => 'ticket not found' } if !$Ticket;
2222 if ( length( $p->{'subject'} || '' ) ) {
2224 if ( $p->{'subject'} ne $Ticket->Subject ) {
2225 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2226 return { 'error' => "unable to set subject: $msg" } if !$val;
2230 if(length($p->{'reply'})) {
2231 my @err_or_res = FS::TicketSystem->correspond_ticket(
2233 'ticket_id' => $p->{'ticket_id'},
2234 'content' => $p->{'reply'},
2237 return { 'error' => 'unable to reply to ticket' }
2238 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2241 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2242 my $err_or_ticket = FS::TicketSystem->get_ticket(
2244 'ticket_id' => $p->{'ticket_id'},
2247 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2248 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2250 return { 'error' => $err_or_ticket };
2253 my @custs = @{$err_or_ticket->{'custs'}};
2254 my @txns = @{$err_or_ticket->{'txns'}};
2257 # superseded by check in get_ticket_object
2258 #return { 'error' => 'invalid ticket requested' }
2259 #unless grep($_ eq $custnum, @custs);
2261 foreach my $txn ( @txns ) {
2262 push @filtered_txns, $txn
2263 if ($txn->{'type'} eq 'EmailRecord'
2264 || $txn->{'type'} eq 'Correspond'
2265 || $txn->{'type'} eq 'Create');
2268 warn "$me get_ticket: successful: \n"
2270 return { 'error' => '',
2271 'transactions' => \@filtered_txns,
2272 'ticket_fields' => $err_or_ticket->{'fields'},
2273 'ticket_id' => $p->{'ticket_id'},
2277 sub adjust_ticket_priority {
2279 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2280 return { 'error' => $session } if $context eq 'error';
2282 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2283 FS::TicketSystem->init;
2284 my $ss_priority = FS::TicketSystem->selfservice_priority;
2286 return { 'error' => 'adjust_ticket_priority configuration error' }
2287 if $FS::TicketSystem::system ne 'RT_Internal'
2290 my $values = $p->{'values'}; #hashref, id => priority value
2293 foreach my $id (keys %$values) {
2294 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2295 my $Ticket = FS::TicketSystem->get_ticket_object('',
2297 'custnum' => $custnum,
2300 $ticket_error{$id} = 'ticket not found';
2304 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2305 # We're not going to implement it for RT_External.
2306 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2307 my $new_value = $values->{$id};
2308 next if $old_value eq $new_value;
2310 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2312 # AddCustomFieldValue works fine (replacing any existing value) if it's
2313 # a single-valued custom field, which it should be. If it's not, you're
2314 # doing something wrong.
2316 if ( length($new_value) ) {
2317 ($val, $msg) = $Ticket->AddCustomFieldValue(
2318 Field => $ss_priority,
2319 Value => $new_value,
2323 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2324 Field => $ss_priority,
2325 Value => $old_value,
2329 $ticket_error{$id} = $msg if !$val;
2330 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2332 return { 'error' => '',
2333 'ticket_error' => \%ticket_error,
2334 %{ customer_info($p) } # send updated customer info back
2340 sub _custoragent_session_custnum {
2343 my($context, $session, $custnum);
2344 if ( $p->{'session_id'} ) {
2346 $context = 'customer';
2347 $session = _cache->get($p->{'session_id'})
2348 or return ( 'error' => "Can't resume session" ); #better error message
2349 $custnum = $session->{'custnum'};
2351 } elsif ( $p->{'agent_session_id'} ) {
2354 my $agent_cache = new FS::ClientAPI_SessionCache( {
2355 'namespace' => 'FS::ClientAPI::Agent',
2357 $session = $agent_cache->get($p->{'agent_session_id'})
2358 or return ( 'error' => "Can't resume session" ); #better error message
2359 $custnum = $p->{'custnum'};
2363 return ( 'error' => "Can't resume session" ); #better error message
2366 ($context, $session, $custnum);