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 ( $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 ) ),
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');
300 'custnum' => $custnum,
301 'access_pkgnum' => $session->{'pkgnum'},
302 'access_svcnum' => $session->{'svcnum'},
309 my($context, $session, $custnum) = _custoragent_session_custnum($p);
310 return { 'error' => $session } if $context eq 'error';
314 my $conf = new FS::Conf;
315 if ($conf->exists('cust_main-require_address2')) {
316 $return{'require_address2'} = '1';
318 $return{'require_address2'} = '';
321 if ( $custnum ) { #customer record
323 my $search = { 'custnum' => $custnum };
324 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
325 my $cust_main = qsearchs('cust_main', $search )
326 or return { 'error' => "unknown custnum $custnum" };
328 if ( $session->{'pkgnum'} ) {
329 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
331 $return{balance} = $cust_main->balance;
334 $return{tickets} = [ ($cust_main->tickets) ];
336 unless ( $session->{'pkgnum'} ) {
339 invnum => $_->invnum,
340 date => time2str("%b %o, %Y", $_->_date),
343 } $cust_main->open_cust_bill;
344 $return{open_invoices} = \@open;
347 $return{small_custview} =
348 small_custview( $cust_main,
349 scalar($conf->config('countrydefault')),
350 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
353 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
355 for (@cust_main_editable_fields) {
356 $return{$_} = $cust_main->get($_);
359 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
360 $return{payinfo} = $cust_main->paymask;
361 @return{'month', 'year'} = $cust_main->paydate_monthyear;
364 $return{'invoicing_list'} =
365 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
366 $return{'postal_invoicing'} =
367 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
369 if (scalar($conf->config('support_packages'))) {
370 my @support_services = ();
371 foreach ($cust_main->support_services) {
372 my $seconds = $_->svc_x->seconds;
373 my $time_remaining = (($seconds < 0) ? '-' : '' ).
374 int(abs($seconds)/3600)."h".
375 sprintf("%02d",(abs($seconds)%3600)/60)."m";
376 my $cust_pkg = $_->cust_pkg;
379 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
380 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
381 push @support_services, { svcnum => $_->svcnum,
382 time => $time_remaining,
387 $return{support_services} = \@support_services;
390 if ( $conf->config('prepayment_discounts-credit_type') ) {
392 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
395 if ( $session->{'svcnum'} ) {
396 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
397 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
400 } elsif ( $session->{'svcnum'} ) { #no customer record
402 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
403 or die "unknown svcnum";
404 $return{name} = $svc_acct->email;
408 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
412 return { 'error' => '',
413 'custnum' => $custnum,
421 my $session = _cache->get($p->{'session_id'})
422 or return { 'error' => "Can't resume session" }; #better error message
424 my $custnum = $session->{'custnum'}
425 or return { 'error' => "no customer record" };
427 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
428 or return { 'error' => "unknown custnum $custnum" };
430 my $new = new FS::cust_main { $cust_main->hash };
431 $new->set( $_ => $p->{$_} )
432 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
435 if (exists($p->{'payby'})) {
436 $p->{'payby'} =~ /^([A-Z]{4})$/
437 or return { 'error' => "illegal_payby " . $p->{'payby'} };
441 if ( $payby =~ /^(CARD|DCRD)$/ ) {
443 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
445 if ( $new->payinfo eq $cust_main->paymask ) {
446 $new->payinfo($cust_main->payinfo);
448 $new->payinfo($p->{'payinfo'});
451 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
453 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
456 $p->{'payinfo1'} =~ /^([\dx]+)$/
457 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
459 $p->{'payinfo2'} =~ /^([\dx]+)$/
460 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
462 $payinfo = $payinfo1. '@'. $payinfo2;
464 $new->payinfo( ($payinfo eq $cust_main->paymask)
465 ? $cust_main->payinfo
469 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
471 } elsif ( $payby =~ /^(BILL)$/ ) {
473 } elsif ( $payby ) { #notyet ready
474 return { 'error' => "unknown payby $payby" };
478 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
479 #false laziness with httemplate/edit/process/cust_main.cgi
480 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
481 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
483 @invoicing_list = $cust_main->invoicing_list;
486 my $error = $new->replace($cust_main, \@invoicing_list);
487 return { 'error' => $error } if $error;
490 return { 'error' => '' };
495 my $session = _cache->get($p->{'session_id'})
496 or return { 'error' => "Can't resume session" }; #better error message
502 my $conf = new FS::Conf;
503 use vars qw($payment_info); #cache for performance
504 unless ( $payment_info ) {
506 my %states = map { $_->state => 1 }
507 qsearch('cust_main_county', {
508 'country' => $conf->config('countrydefault') || 'US'
511 my %cust_paybys = map { $_ => 1 }
512 map { FS::payby->payby2payment($_) }
513 $conf->config('signup_server-payby');
515 my @cust_paybys = keys %cust_paybys;
519 #list all counties/states/countries
520 'cust_main_county' =>
521 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
523 #shortcut for one-country folks
525 [ sort { $a cmp $b } keys %states ],
527 'card_types' => card_types(),
529 'paytypes' => [ @FS::cust_main::paytypes ],
531 'paybys' => [ $conf->config('signup_server-payby') ],
532 'cust_paybys' => \@cust_paybys,
534 'stateid_label' => FS::Msgcat::_gettext('stateid'),
535 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
537 'show_ss' => $conf->exists('show_ss'),
538 'show_stateid' => $conf->exists('show_stateid'),
539 'show_paystate' => $conf->exists('show_bankstate'),
541 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
550 my %return = %$payment_info;
552 my $custnum = $session->{'custnum'};
554 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
555 or return { 'error' => "unknown custnum $custnum" };
557 $return{'hide_payment_fields'} = [
559 my $pg = payment_gateway($cust_main, $_);
560 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
561 } @{ $return{cust_paybys} }
564 $return{balance} = $cust_main->balance; #XXX pkg-balances?
566 $return{payname} = $cust_main->payname
567 || ( $cust_main->first. ' '. $cust_main->get('last') );
569 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
571 $return{payby} = $cust_main->payby;
572 $return{stateid_state} = $cust_main->stateid_state;
574 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
575 $return{card_type} = cardtype($cust_main->payinfo);
576 $return{payinfo} = $cust_main->paymask;
578 @return{'month', 'year'} = $cust_main->paydate_monthyear;
582 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
583 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
584 $return{payinfo1} = $payinfo1;
585 $return{payinfo2} = $payinfo2;
586 $return{paytype} = $cust_main->paytype;
587 $return{paystate} = $cust_main->paystate;
591 if ( $conf->config('prepayment_discounts-credit_type') ) {
593 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
596 #doubleclick protection
598 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
600 return { 'error' => '',
606 #some false laziness with httemplate/process/payment.cgi - look there for
607 #ACH and CVV support stuff
608 sub process_payment {
612 my $session = _cache->get($p->{'session_id'})
613 or return { 'error' => "Can't resume session" }; #better error message
617 my $custnum = $session->{'custnum'};
619 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
620 or return { 'error' => "unknown custnum $custnum" };
622 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
623 or return { 'error' => gettext('illegal_amount') };
625 return { error => 'Amount must be greater than 0' } unless $amount > 0;
627 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
628 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
629 my $discount_term = $1;
631 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
632 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
635 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
636 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
639 $p->{'payby'} ||= 'CARD';
640 $p->{'payby'} =~ /^([A-Z]{4})$/
641 or return { 'error' => "illegal_payby " . $p->{'payby'} };
644 #false laziness w/process/payment.cgi
648 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
650 $p->{'payinfo1'} =~ /^([\dx]+)$/
651 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
653 $p->{'payinfo2'} =~ /^([\dx]+)$/
654 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
656 $payinfo = $payinfo1. '@'. $payinfo2;
658 $payinfo = $cust_main->payinfo
659 if $cust_main->paymask eq $payinfo;
661 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
663 $payinfo = $p->{'payinfo'};
665 #more intelligent mathing will be needed here if you change
666 #card_masking_method and don't remove existing paymasks
667 $payinfo = $cust_main->payinfo
668 if $cust_main->paymask eq $payinfo;
671 $payinfo =~ /^(\d{13,16})$/
672 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
676 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
677 return { 'error' => gettext('unknown_card_type') }
678 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
680 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
681 if ( cardtype($payinfo) eq 'American Express card' ) {
682 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
683 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
686 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
687 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
693 die "unknown payby $payby";
697 'CARD' => [ qw( paystart_month paystart_year payissue payip
698 address1 address2 city state zip country ) ],
699 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
702 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
704 'payinfo' => $payinfo,
705 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
706 'payname' => $payname,
707 'paybatch' => $paybatch, #this doesn't actually do anything
709 'paynum_ref' => \$paynum,
710 'pkgnum' => $session->{'pkgnum'},
711 'discount_term' => $discount_term,
713 map { $_ => $p->{$_} } @{ $payby2fields{$payby} }
715 return { 'error' => $error } if $error;
717 $cust_main->apply_payments;
719 if ( $p->{'save'} ) {
720 my $new = new FS::cust_main { $cust_main->hash };
721 if ($payby eq 'CARD' || $payby eq 'DCRD') {
722 $new->set( $_ => $p->{$_} )
723 foreach qw( payname paystart_month paystart_year payissue payip
724 address1 address2 city state zip country );
725 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
726 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
727 $new->set( $_ => $p->{$_} )
728 foreach qw( payname payip paytype paystate
729 stateid stateid_state );
730 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
732 $new->set( 'payinfo' => $cust_main->card_token || $payinfo );
733 $new->set( 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01' );
734 my $error = $new->replace($cust_main);
736 #no, this causes customers to process their payments again
737 #return { 'error' => $error };
738 #XXX just warn verosely for now so i can figure out how these happen in
739 # the first place, eventually should redirect them to the "change
740 #address" page but indicate the payment did process??
741 delete($p->{'payinfo'}); #don't want to log this!
742 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
743 "NEW: ". Dumper($new)."\n".
744 "OLD: ". Dumper($cust_main)."\n".
745 "PACKET: ". Dumper($p)."\n";
752 my $receipt_html = '';
754 # currently supported for realtime CC only; send receipt data to SS
755 my $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
758 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
761 <TD ALIGN="right">Payment#</TD>
762 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
766 <TD ALIGN="right">Date</TD>
768 <TD BGCOLOR="#FFFFFF"><B>! .
769 time2str("%a %b %o, %Y %r", $cust_pay->_date)
775 <TD ALIGN="right">Amount</TD>
776 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paid . qq!</B></TD>
781 <TD ALIGN="right">Payment method</TD>
782 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
791 return { 'error' => '', 'receipt_html' => $receipt_html, };
795 sub realtime_collect {
798 my $session = _cache->get($p->{'session_id'})
799 or return { 'error' => "Can't resume session" }; #better error message
801 my $custnum = $session->{'custnum'};
803 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
804 or return { 'error' => "unknown custnum $custnum" };
807 if ( $p->{'amount'} ) {
808 $amount = $p->{'amount'};
810 elsif ( $session->{'pkgnum'} ) {
811 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
814 $amount = $cust_main->balance;
817 my $error = $cust_main->realtime_collect(
818 'method' => $p->{'method'},
820 'pkgnum' => $session->{'pkgnum'},
821 'session_id' => $p->{'session_id'},
825 return { 'error' => $error } unless ref( $error );
827 return { 'error' => '', amount => $amount, %$error };
830 sub process_payment_order_pkg {
833 my $hr = process_payment($p);
834 return $hr if $hr->{'error'};
839 sub process_payment_order_renew {
842 my $hr = process_payment($p);
843 return $hr if $hr->{'error'};
852 my $session = _cache->get($p->{'session_id'})
853 or return { 'error' => "Can't resume session" }; #better error message
857 my $custnum = $session->{'custnum'};
859 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
860 or return { 'error' => "unknown custnum $custnum" };
862 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
863 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
871 return { 'error' => $error } if $error;
873 return { 'error' => '',
875 'seconds' => $seconds,
876 'duration' => duration_exact($seconds),
877 'upbytes' => $upbytes,
878 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
879 'downbytes' => $downbytes,
880 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
881 'totalbytes'=> $totalbytes,
882 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
889 my $session = _cache->get($p->{'session_id'})
890 or return { 'error' => "Can't resume session" }; #better error message
892 my $custnum = $session->{'custnum'};
894 my $invnum = $p->{'invnum'};
896 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
897 'custnum' => $custnum } )
898 or return { 'error' => "Can't find invnum" };
902 return { 'error' => '',
904 'invoice_text' => join('', $cust_bill->print_text ),
905 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
913 #sessioning for this? how do we get the session id to the backend invoice
914 # template so it can add it to the link, blah
917 if ( $p->{'invnum'} ) {
918 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
919 or return { 'error' => 'unknown invnum' };
920 $agentnum = $cust_bill->cust_main->agentnum;
923 my $templatename = $p->{'template'} || $p->{'templatename'};
925 #false laziness-ish w/view/cust_bill-logo.cgi
927 my $conf = new FS::Conf;
928 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
929 $templatename = "_$1";
934 my $filename = "logo$templatename.png";
936 return { 'error' => '',
937 'logo' => $conf->config_binary($filename, $agentnum),
938 'content_type' => 'image/png', #should allow gif, jpg too
945 my $session = _cache->get($p->{'session_id'})
946 or return { 'error' => "Can't resume session" }; #better error message
948 my $custnum = $session->{'custnum'};
950 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
951 or return { 'error' => "unknown custnum $custnum" };
953 my @cust_bill = $cust_main->cust_bill;
955 return { 'error' => '',
956 'invoices' => [ map { { 'invnum' => $_->invnum,
957 '_date' => $_->_date,
958 'date' => time2str("%b %o, %Y", $_->_date),
967 my $session = _cache->get($p->{'session_id'})
968 or return { 'error' => "Can't resume session" }; #better error message
970 my $custnum = $session->{'custnum'};
972 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
973 or return { 'error' => "unknown custnum $custnum" };
975 my @errors = $cust_main->cancel( 'quiet'=>1 );
977 my $error = scalar(@errors) ? join(' / ', @errors) : '';
979 return { 'error' => $error };
986 my($context, $session, $custnum) = _custoragent_session_custnum($p);
987 return { 'error' => $session } if $context eq 'error';
989 my $search = { 'custnum' => $custnum };
990 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
991 my $cust_main = qsearchs('cust_main', $search )
992 or return { 'error' => "unknown custnum $custnum" };
994 my $conf = new FS::Conf;
996 # the duplication below is necessary:
997 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
998 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
999 # non-backwards-compatible change breaking the software of anyone using the API
1000 # instead of the stock selfservice
1001 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1002 if( $conf->exists('selfservice_server-view-wholesale') ) {
1003 return { 'svcnum' => $session->{'svcnum'},
1004 'custnum' => $custnum,
1005 'cust_pkg' => [ map {
1007 part_pkg => [ map $_->hashref, $_->part_pkg ],
1009 [ map $_->hashref, $_->available_part_svc ],
1011 [ map { my $ref = { $_->hash,
1012 label => [ $_->label ],
1014 $ref->{_password} = $_->svc_x->_password
1015 if $context eq 'agent'
1016 && $conf->exists('agent-showpasswords')
1017 && $_->part_svc->svcdb eq 'svc_acct';
1022 } $cust_main->cust_pkg
1025 small_custview( $cust_main, $conf->config('countrydefault') ),
1026 'wholesale_view' => 1,
1027 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1028 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1029 'lnp' => $conf->exists('svc_phone-lnp'),
1033 { 'svcnum' => $session->{'svcnum'},
1034 'custnum' => $custnum,
1035 'cust_pkg' => [ map {
1039 [ map $_->hashref, $_->available_part_svc ],
1041 [ map { my $ref = { $_->hash,
1042 label => [ $_->label ],
1044 $ref->{_password} = $_->svc_x->_password
1045 if $context eq 'agent'
1046 && $conf->exists('agent-showpasswords')
1047 && $_->part_svc->svcdb eq 'svc_acct';
1048 $ref->{svchash} = { $_->svc_x->hash } if
1049 $_->part_svc->svcdb eq 'svc_phone';
1050 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1051 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1056 } $cust_main->ncancelled_pkgs
1059 small_custview( $cust_main, $conf->config('countrydefault') ),
1067 my $conf = new FS::Conf;
1069 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1070 return { 'error' => $session } if $context eq 'error';
1072 my $search = { 'custnum' => $custnum };
1073 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1074 my $cust_main = qsearchs('cust_main', $search )
1075 or return { 'error' => "unknown custnum $custnum" };
1078 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1079 foreach my $cust_pkg ( $p->{'ncancelled'}
1080 ? $cust_main->ncancelled_pkgs
1081 : $cust_main->unsuspended_pkgs ) {
1082 next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1083 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1085 if ( $p->{'svcdb'} ) {
1086 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1088 : ref($p->{'svcdb'}) eq 'ARRAY'
1089 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1090 : { $p->{'svcdb'} => 1 };
1091 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1094 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1098 'svcnum' => $session->{'svcnum'},
1099 'custnum' => $custnum,
1100 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1103 my $svc_x = $_->svc_x;
1104 my($label, $value) = $_->label;
1105 my $svcdb = $_->part_svc->svcdb;
1106 my $part_pkg = $_->cust_pkg->part_pkg;
1109 'svcnum' => $_->svcnum,
1115 if ( $svcdb eq 'svc_acct' ) {
1118 'username' => $svc_x->username,
1119 'email' => $svc_x->email,
1120 'seconds' => $svc_x->seconds,
1121 'upbytes' => display_bytecount($svc_x->upbytes),
1122 'downbytes' => display_bytecount($svc_x->downbytes),
1123 'totalbytes' => display_bytecount($svc_x->totalbytes),
1125 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1126 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1127 'recharge_upbytes' =>
1128 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1129 'recharge_downbytes' =>
1130 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1131 'recharge_totalbytes' =>
1132 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1136 } elsif ( $svcdb eq 'svc_phone' ) {
1150 sub _list_svc_usage {
1151 my($svc_acct, $begin, $end) = @_;
1153 foreach my $part_export (
1154 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1155 qw( sqlradius sqlradius_withdomain )
1157 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1162 sub list_svc_usage {
1163 _usage_details(\&_list_svc_usage, @_);
1166 sub _list_support_usage {
1167 my($svc_acct, $begin, $end) = @_;
1169 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1170 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1172 push @usage, { 'seconds' => $_->seconds,
1173 'support' => $_->support,
1174 '_date' => $_->_date,
1175 'id' => $_->transaction_id,
1176 'creator' => $_->creator,
1177 'subject' => $_->subject,
1178 'status' => $_->status,
1179 'ticketid' => $_->ticketid,
1185 sub list_support_usage {
1186 _usage_details(\&_list_support_usage, @_);
1189 sub _list_cdr_usage {
1190 my($svc_phone, $begin, $end) = @_;
1191 map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1192 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1195 sub list_cdr_usage {
1197 _usage_details( \&_list_cdr_usage, $p,
1198 'svcdb' => 'svc_phone',
1202 sub _usage_details {
1203 my($callback, $p, %opt) = @_;
1205 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1206 return { 'error' => $session } if $context eq 'error';
1208 my $search = { 'svcnum' => $p->{'svcnum'} };
1209 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1211 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1213 my $svc_x = qsearchs( $svcdb, $search );
1214 return { 'error' => 'No service selected in list_svc_usage' }
1217 my $header = $svcdb eq 'svc_phone'
1218 ? [ split(',', FS::cdr::invoice_header('default') ) ] #XXX
1221 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1222 my $freq = $cust_pkg->part_pkg->freq;
1223 my $start = $cust_pkg->setup;
1224 #my $end = $cust_pkg->bill; # or time?
1227 unless ( $p->{beginning} ) {
1228 $p->{beginning} = $cust_pkg->last_bill;
1229 $p->{ending} = $end;
1232 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1234 #kinda false laziness with FS::cust_main::bill, but perhaps
1235 #we should really change this bit to DateTime and DateTime::Duration
1237 #change this bit to use Date::Manip? CAREFUL with timezones (see
1238 # mailing list archive)
1239 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1240 (localtime($p->{ending}) )[0,1,2,3,4,5];
1241 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1242 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1244 if ( $freq =~ /^\d+$/ ) {
1246 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1248 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1249 } elsif ( $freq =~ /^(\d+)w$/ ) {
1251 $nmday += $weeks * 7;
1252 $pmday -= $weeks * 7;
1253 } elsif ( $freq =~ /^(\d+)d$/ ) {
1257 } elsif ( $freq =~ /^(\d+)h$/ ) {
1262 return { 'error' => "unparsable frequency: ". $freq };
1265 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1266 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1270 'svcnum' => $p->{svcnum},
1271 'beginning' => $p->{beginning},
1272 'ending' => $p->{ending},
1273 'previous' => ($previous > $start) ? $previous : $start,
1274 'next' => ($next < $end) ? $next : $end,
1275 'header' => $header,
1283 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1284 return { 'error' => $session } if $context eq 'error';
1286 my $search = { 'custnum' => $custnum };
1287 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1288 my $cust_main = qsearchs('cust_main', $search )
1289 or return { 'error' => "unknown custnum $custnum" };
1291 my $status = $cust_main->status;
1292 #false laziness w/ClientAPI/Signup.pm
1294 my $cust_pkg = new FS::cust_pkg ( {
1295 'custnum' => $custnum,
1296 'pkgpart' => $p->{'pkgpart'},
1298 my $error = $cust_pkg->check;
1299 return { 'error' => $error } if $error;
1302 unless ( $p->{'svcpart'} eq 'none' ) {
1306 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1308 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1309 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1310 $svcdb = $part_svc->svcdb;
1312 $svcdb = 'svc_acct';
1314 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1317 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
1318 'svc_domain' => [ qw( domain ) ],
1319 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
1320 'svc_external' => [ qw( id title ) ],
1321 'svc_pbx' => [ qw( id title ) ],
1324 my $svc_x = "FS::$svcdb"->new( {
1325 'svcpart' => $svcpart,
1326 map { $_ => $p->{$_} } @{$fields{$svcdb}}
1329 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1332 while ( length($p->{"snarf_machine$snarfnum"}) ) {
1333 my $acct_snarf = new FS::acct_snarf ( {
1334 'machine' => $p->{"snarf_machine$snarfnum"},
1335 'protocol' => $p->{"snarf_protocol$snarfnum"},
1336 'username' => $p->{"snarf_username$snarfnum"},
1337 '_password' => $p->{"snarf_password$snarfnum"},
1340 push @acct_snarf, $acct_snarf;
1342 $svc_x->child_objects( \@acct_snarf );
1345 my $y = $svc_x->setdefault; # arguably should be in new method
1346 return { 'error' => $y } if $y && !ref($y);
1348 $error = $svc_x->check;
1349 return { 'error' => $error } if $error;
1356 tie my %hash, 'Tie::RefHash';
1357 %hash = ( $cust_pkg => \@svc );
1359 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1360 return { 'error' => $error } if $error;
1362 my $conf = new FS::Conf;
1363 if ( $conf->exists('signup_server-realtime') ) {
1365 my $bill_error = _do_bop_realtime( $cust_main, $status );
1368 $cust_pkg->cancel('quiet'=>1);
1371 $cust_pkg->reexport;
1375 $cust_pkg->reexport;
1378 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1380 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1387 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1388 return { 'error' => $session } if $context eq 'error';
1390 my $search = { 'custnum' => $custnum };
1391 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1392 my $cust_main = qsearchs('cust_main', $search )
1393 or return { 'error' => "unknown custnum $custnum" };
1395 my $status = $cust_main->status;
1396 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1397 or return { 'error' => "unknown package $p->{pkgnum}" };
1400 my $error = FS::cust_pkg::order( $custnum,
1406 my $conf = new FS::Conf;
1407 if ( $conf->exists('signup_server-realtime') ) {
1409 my $bill_error = _do_bop_realtime( $cust_main, $status );
1412 $newpkg[0]->suspend;
1415 $newpkg[0]->reexport;
1419 $newpkg[0]->reexport;
1422 return { error => '', pkgnum => $cust_pkg->pkgnum };
1426 sub order_recharge {
1429 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1430 return { 'error' => $session } if $context eq 'error';
1432 my $search = { 'custnum' => $custnum };
1433 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1434 my $cust_main = qsearchs('cust_main', $search )
1435 or return { 'error' => "unknown custnum $custnum" };
1437 my $status = $cust_main->status;
1438 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1439 or return { 'error' => "unknown service " . $p->{'svcnum'} };
1441 my $svc_x = $cust_svc->svc_x;
1442 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1445 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
1446 qw ( recharge_seconds recharge_upbytes recharge_downbytes
1447 recharge_totalbytes );
1448 my $amount = $part_pkg->option('recharge_amount', 1);
1450 my ($l, $v, $d) = $cust_svc->label; # blah
1451 my $pkg = "Recharge $v";
1453 my $bill_error = $cust_main->charge($amount, $pkg,
1454 "time: $vhash{seconds}, up: $vhash{upbytes}," .
1455 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1456 $part_pkg->taxclass); #meh
1458 my $conf = new FS::Conf;
1459 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1461 $bill_error = _do_bop_realtime( $cust_main, $status );
1466 my $error = $svc_x->recharge (\%vhash);
1467 return { 'error' => $error } if $error;
1471 my $error = $bill_error;
1472 $error ||= $svc_x->recharge (\%vhash);
1473 return { 'error' => $error } if $error;
1476 return { error => '', svc => $cust_svc->part_svc->svc };
1480 sub _do_bop_realtime {
1481 my ($cust_main, $status) = (shift, shift);
1483 my $old_balance = $cust_main->balance;
1485 my $bill_error = $cust_main->bill
1486 || $cust_main->apply_payments_and_credits
1487 || $cust_main->realtime_collect('selfservice' => 1);
1489 if ( $cust_main->balance > $old_balance
1490 && $cust_main->balance > 0
1491 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1492 1 : $status eq 'suspended' ) ) {
1493 #this makes sense. credit is "un-doing" the invoice
1494 my $conf = new FS::Conf;
1495 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1496 'self-service decline',
1497 'reason_type' => $conf->config('signup_credit_type'),
1499 $cust_main->apply_credits( 'order' => 'newest' );
1501 return { 'error' => '_decline', 'bill_error' => $bill_error };
1510 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1511 return { 'error' => $session } if $context eq 'error';
1513 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1514 or return { 'error' => "unknown custnum $custnum" };
1516 my @cust_pkg = sort { $a->bill <=> $b->bill }
1517 grep { $_->part_pkg->freq ne '0' }
1518 $cust_main->ncancelled_pkgs;
1520 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1522 my $total = $cust_main->balance;
1525 my $bill = $_->bill;
1526 $total += $_->part_pkg->base_recur($_, \$bill);
1527 my $renew_date = $_->part_pkg->add_freq($_->bill);
1529 'pkgnum' => $_->pkgnum,
1530 'amount' => sprintf('%.2f', $total),
1531 'bill_date' => $_->bill,
1532 'bill_date_pretty' => time2str('%x', $_->bill),
1533 'renew_date' => $renew_date,
1534 'renew_date_pretty' => time2str('%x', $renew_date),
1535 'expire_date' => $_->expire,
1536 'expire_date_pretty' => time2str('%x', $_->expire),
1541 return { 'dates' => \@array };
1545 sub payment_info_renew_info {
1547 my $renew_info = renew_info($p);
1548 my $payment_info = payment_info($p);
1549 return { %$renew_info,
1557 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1558 return { 'error' => $session } if $context eq 'error';
1560 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1561 or return { 'error' => "unknown custnum $custnum" };
1563 my $date = $p->{'date'};
1567 #freeside-daily -n -d $date fs_daily $custnum
1568 $cust_main->bill_and_collect( 'time' => $date,
1569 'invoice_time' => $now,
1570 'actual_time' => $now,
1571 'check_freq' => '1d',
1574 return { 'error' => '' };
1578 # these are basically the same
1579 sub cancel_pkg { alter_pkg(shift, 'cancel', 'quiet' => 1) }
1581 my $conf = new FS::Conf;
1582 my $reasonnum = $conf->config('selfservice-self_suspend_reason')
1583 or return { 'error' => "Permission denied" };
1584 alter_pkg(shift, 'suspend', 'reason' => $reasonnum)
1590 my $session = _cache->get($p->{'session_id'})
1591 or return { 'error' => "Can't resume session" }; #better error message
1593 my $custnum = $session->{'custnum'};
1595 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1596 or return { 'error' => "unknown custnum $custnum" };
1598 my $pkgnum = $p->{'pkgnum'};
1600 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1601 'pkgnum' => $pkgnum, } )
1602 or return { 'error' => "unknown pkgnum $pkgnum" };
1604 my $error = $cust_pkg->$method(@_);
1605 return { 'error' => $error };
1609 sub provision_phone {
1612 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1614 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1615 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1616 return { 'error' => $session } if $context eq 'error';
1618 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1619 return { 'error' => 'service not found' } unless $svc_phone;
1620 return { 'error' => 'invalid svcnum' }
1621 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1623 $svc_phone->email($p->{'email'})
1624 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1625 $svc_phone->forwarddst($p->{'forwarddst'})
1626 if $svc_phone->forwarddst ne $p->{'forwarddst'}
1627 && $p->{'forwarddst'} =~ /^(\d+|)$/;
1628 return { 'error' => $svc_phone->replace };
1632 unless($p->{'lnp'}) {
1633 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1634 $p->{'lnp_status'} = "portingin";
1635 return _provision( 'FS::svc_phone',
1636 [qw(lnp_desired_due_date lnp_other_provider
1637 lnp_other_provider_account phonenum countrycode lnp_status)],
1638 [qw(phonenum countrycode)],
1645 unless (scalar(@bulkdid)) {
1646 return _provision( 'FS::svc_phone',
1647 [qw(phonenum countrycode)],
1648 [qw(phonenum countrycode)],
1654 # bulk DID order case
1656 foreach my $did ( @bulkdid ) {
1657 $did =~ s/[^0-9]//g;
1658 $error = _provision( 'FS::svc_phone',
1659 [qw(phonenum countrycode)],
1660 [qw(phonenum countrycode)],
1662 'pkgnum' => $p->{'pkgnum'},
1663 'svcpart' => $p->{'svcpart'},
1665 'countrycode' => $p->{'countrycode'},
1666 'session_id' => $p->{'session_id'},
1669 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1671 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1674 sub provision_acct {
1676 warn "provision_acct called\n"
1679 return { 'error' => gettext('passwords_dont_match') }
1680 if $p->{'_password'} ne $p->{'_password2'};
1681 return { 'error' => gettext('empty_password') }
1682 unless length($p->{'_password'});
1684 if ($p->{'domsvc'}) {
1685 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1686 qw ( svcpart pkgnum ) );
1687 return { 'error' => gettext('invalid_domain') }
1688 unless ($domains{$p->{'domsvc'}});
1691 warn "provision_acct calling _provision\n"
1693 _provision( 'FS::svc_acct',
1694 [qw(username _password domsvc)],
1695 [qw(username _password domsvc)],
1701 sub provision_external {
1703 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1704 _provision( 'FS::svc_external',
1713 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1714 warn "_provision called for $class\n"
1717 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1718 return { 'error' => $session } if $context eq 'error';
1720 my $search = { 'custnum' => $custnum };
1721 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1722 my $cust_main = qsearchs('cust_main', $search )
1723 or return { 'error' => "unknown custnum $custnum" };
1725 my $pkgnum = $p->{'pkgnum'};
1727 warn "searching for custnum $custnum pkgnum $pkgnum\n"
1729 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1730 'pkgnum' => $pkgnum,
1732 or return { 'error' => "unknown pkgnum $pkgnum" };
1734 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1736 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1737 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1739 warn "creating $class record\n"
1741 my $svc_x = $class->new( {
1742 'pkgnum' => $p->{'pkgnum'},
1743 'svcpart' => $p->{'svcpart'},
1744 map { $_ => $p->{$_} } @$fields
1746 warn "inserting $class record\n"
1748 my $error = $svc_x->insert;
1751 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1753 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1756 my $return = { 'svc' => $part_svc->svc,
1758 map { $_ => $svc_x->get($_) } @$return_fields
1760 warn "_provision returning ". Dumper($return). "\n"
1769 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1770 return { 'error' => $session } if $context eq 'error';
1772 my $search = { 'custnum' => $custnum };
1773 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1774 my $cust_main = qsearchs('cust_main', $search )
1775 or return { 'error' => "unknown custnum $custnum" };
1777 my $pkgnum = $p->{'pkgnum'};
1779 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1780 'pkgnum' => $pkgnum,
1782 or return { 'error' => "unknown pkgnum $pkgnum" };
1784 my $svcpart = $p->{'svcpart'};
1786 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1787 'svcpart' => $svcpart, } )
1788 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1789 my $part_svc = $pkg_svc->part_svc;
1791 my $conf = new FS::Conf;
1794 'svc' => $part_svc->svc,
1795 'svcdb' => $part_svc->svcdb,
1796 'pkgnum' => $pkgnum,
1797 'svcpart' => $svcpart,
1798 'custnum' => $custnum,
1800 'security_phrase' => 0, #XXX !
1801 'svc_acct_pop' => [], #XXX !
1803 'init_popstate' => '',
1808 small_custview( $cust_main, $conf->config('countrydefault') ),
1812 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
1813 && $ret->{'svcdb'} eq 'svc_phone') {
1814 $ret->{'svcnum'} = $p->{'svcnum'};
1815 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1816 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
1817 $ret->{'email'} = $svc_phone->email;
1818 $ret->{'forwarddst'} = $svc_phone->forwarddst;
1825 sub unprovision_svc {
1828 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1829 return { 'error' => $session } if $context eq 'error';
1831 my $search = { 'custnum' => $custnum };
1832 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1833 my $cust_main = qsearchs('cust_main', $search )
1834 or return { 'error' => "unknown custnum $custnum" };
1836 my $svcnum = $p->{'svcnum'};
1838 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
1839 or return { 'error' => "unknown svcnum $svcnum" };
1841 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1842 unless $cust_svc->cust_pkg->custnum == $custnum;
1844 my $conf = new FS::Conf;
1846 return { 'svc' => $cust_svc->part_svc->svc,
1847 'error' => $cust_svc->cancel,
1849 small_custview( $cust_main, $conf->config('countrydefault') ),
1854 sub myaccount_passwd {
1856 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1857 return { 'error' => $session } if $context eq 'error';
1859 return { 'error' => "New passwords don't match." }
1860 if $p->{'new_password'} ne $p->{'new_password2'};
1862 return { 'error' => 'Enter new password' }
1863 unless length($p->{'new_password'});
1865 #my $search = { 'custnum' => $custnum };
1866 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1867 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1868 my $search = " AND custnum = $1";
1869 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1871 my $svc_acct = qsearchs( {
1872 'table' => 'svc_acct',
1873 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1874 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
1875 'LEFT JOIN cust_main USING ( custnum ) ',
1876 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
1877 'extra_sql' => $search, #important
1879 or return { 'error' => "Service not found" };
1881 $svc_acct->_password($p->{'new_password'});
1882 my $error = $svc_acct->replace();
1884 my($label, $value) = $svc_acct->cust_svc->label;
1886 return { 'error' => $error,
1895 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1896 return { 'error' => $session } if $context eq 'error';
1898 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
1899 FS::TicketSystem->init();
1901 my $conf = new FS::Conf;
1902 my $queue = $p->{'queue'}
1903 || $conf->config('ticket_system-selfservice_queueid')
1904 || $conf->config('ticket_system-default_queueid');
1906 warn "$me create_ticket: creating ticket\n" if $DEBUG;
1907 my $err_or_ticket = FS::TicketSystem->create_ticket(
1908 '', #create RT session based on FS CurrentUser (fs_selfservice)
1910 'custnum' => $custnum,
1911 'svcnum' => $session->{'svcnum'},
1912 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
1915 if ( ref($err_or_ticket) ) {
1916 warn "$me create_ticket: sucessful: ". $err_or_ticket->id. "\n"
1918 return { 'error' => '',
1919 'ticket_id' => $err_or_ticket->id,
1922 warn "$me create_ticket: unsucessful: $err_or_ticket\n"
1924 return { 'error' => $err_or_ticket };
1932 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1933 return { 'error' => $session } if $context eq 'error';
1935 return { error => 'requested format not implemented' }
1936 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
1938 my $conf = new FS::Conf;
1939 my $age_threshold = 0;
1940 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
1941 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
1943 my $search = { 'custnum' => $custnum };
1944 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1945 my $cust_main = qsearchs('cust_main', $search )
1946 or return { 'error' => "unknown custnum $custnum" };
1948 # does it make more sense to just run one sql query for this instead of all the
1949 # insanity below? would increase performance greately for large data sets?
1951 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1952 my @part_svc = $cust_pkg->part_svc;
1953 foreach my $part_svc ( @part_svc ) {
1954 if($part_svc->svcdb eq 'svc_phone'){
1955 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
1956 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
1957 push @svc_phone, $cust_pkg_svc->svc_x
1958 if $cust_pkg_svc->date_inserted >= $age_threshold;
1966 my($xls_r,$xls_c) = (0,0);
1969 my @fields = qw( countrycode phonenum pin sip_password phone_name );
1970 if($p->{'format'} eq 'csv') {
1971 $csv = new Text::CSV_XS { 'always_quote' => 1,
1974 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
1975 $content .= $csv->string;
1977 elsif($p->{'format'} eq 'xls') {
1978 my $XLS1 = new IO::Scalar \$content;
1979 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
1980 or return { 'error' => "Error opening .xls file: $!" };
1981 $xls = $xls_workbook->add_worksheet('DIDs');
1982 foreach ( @fields ) {
1983 $xls->write(0,$xls_c++,$_);
1988 foreach my $svc_phone ( @svc_phone ) {
1989 my @cols = map { $svc_phone->$_ } @fields;
1990 if($p->{'format'} eq 'csv') {
1991 return { 'error' => 'Unable to create CSV' }
1992 unless $csv->combine(@cols);
1993 $content .= $csv->string;
1995 elsif($p->{'format'} eq 'xls') {
1998 $xls->write($xls_r,$xls_c++,$_);
2004 $xls_workbook->close() if $p->{'format'} eq 'xls';
2006 { content => $content, format => $p->{'format'}, };
2011 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2012 return { 'error' => $session } if $context eq 'error';
2014 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2015 FS::TicketSystem->init();
2017 if(length($p->{'reply'})) {
2018 # currently this allows anyone to correspond on any ticket as fs_selfservice
2020 my @err_or_res = FS::TicketSystem->correspond_ticket(
2021 '', #create RT session based on FS CurrentUser (fs_selfservice)
2022 'ticket_id' => $p->{'ticket_id'},
2023 'content' => $p->{'reply'},
2026 return { 'error' => 'unable to reply to ticket' }
2027 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2030 warn "$me get_ticket: getting ticket\n" if $DEBUG;
2031 my $err_or_ticket = FS::TicketSystem->get_ticket(
2032 '', #create RT session based on FS CurrentUser (fs_selfservice)
2033 'ticket_id' => $p->{'ticket_id'},
2036 if ( ref($err_or_ticket) ) {
2038 # since we're bypassing the RT security/permissions model by always using
2039 # fs_selfservice as the RT user (as opposed to a requestor, which we
2040 # can't do since we want all tickets linked to a cust), we check below whether
2041 # the requested ticket was actually linked to this customer
2042 my @custs = @{$err_or_ticket->{'custs'}};
2043 my @txns = @{$err_or_ticket->{'txns'}};
2046 return { 'error' => 'no customer' } unless ( $custnum && scalar(@custs) );
2048 return { 'error' => 'invalid ticket requested' }
2049 unless grep($_ eq $custnum, @custs);
2051 foreach my $txn ( @txns ) {
2052 push @filtered_txns, $txn
2053 if ($txn->{'type'} eq 'EmailRecord'
2054 || $txn->{'type'} eq 'Correspond'
2055 || $txn->{'type'} eq 'Create');
2058 warn "$me get_ticket: sucessful: \n"
2060 return { 'error' => '',
2061 'transactions' => \@filtered_txns,
2062 'ticket_id' => $p->{'ticket_id'},
2065 warn "$me create_ticket: unsucessful: $err_or_ticket\n"
2067 return { 'error' => $err_or_ticket };
2074 sub _custoragent_session_custnum {
2077 my($context, $session, $custnum);
2078 if ( $p->{'session_id'} ) {
2080 $context = 'customer';
2081 $session = _cache->get($p->{'session_id'})
2082 or return ( 'error' => "Can't resume session" ); #better error message
2083 $custnum = $session->{'custnum'};
2085 } elsif ( $p->{'agent_session_id'} ) {
2088 my $agent_cache = new FS::ClientAPI_SessionCache( {
2089 'namespace' => 'FS::ClientAPI::Agent',
2091 $session = $agent_cache->get($p->{'agent_session_id'})
2092 or return ( 'error' => "Can't resume session" ); #better error message
2093 $custnum = $p->{'custnum'};
2097 return ( 'error' => "Can't resume session" ); #better error message
2100 ($context, $session, $custnum);