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;
30 use FS::cust_main_county;
33 use FS::acct_rt_transaction;
38 use Spreadsheet::WriteExcel;
41 $me = '[FS::ClientAPI::MyAccount]';
43 use vars qw( @cust_main_editable_fields );
44 @cust_main_editable_fields = qw(
45 first last company address1 address2 city
46 county state zip country daytime night fax
47 ship_first ship_last ship_company ship_address1 ship_address2 ship_city
48 ship_state ship_zip ship_country ship_daytime ship_night ship_fax
49 payby payinfo payname paystart_month paystart_year payissue payip
50 ss paytype paystate stateid stateid_state
54 $cache ||= new FS::ClientAPI_SessionCache( {
55 'namespace' => 'FS::ClientAPI::MyAccount',
62 my($context, $session, $custnum) = _custoragent_session_custnum($p);
63 #return { 'error' => $session } if $context eq 'error';
66 if ( $context eq 'customer' ) {
68 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
71 $sth->execute($custnum) or die $sth->errstr;
73 $agentnum = $sth->fetchrow_arrayref->[0]
74 or die "no agentnum for custnum $custnum";
76 #} elsif ( $context eq 'agent' ) {
77 } elsif ( $p->{'agentnum'} =~ /^(\d+)$/ ) {
81 my $conf = new FS::Conf;
83 #false laziness w/Signup.pm
85 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
87 if ( $skin_info_cache_agent ) {
89 warn "$me loading cached skin info for agentnum $agentnum\n"
94 warn "$me populating skin info cache for agentnum $agentnum\n"
97 $skin_info_cache_agent = {
98 'agentnum' => $agentnum,
99 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
100 qw( company_name ) ),
101 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
102 qw( body_bgcolor box_bgcolor
103 text_color link_color vlink_color hlink_color alink_color
104 font title_color title_align title_size menu_bgcolor menu_fontsize
107 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
108 qw( menu_skipblanks menu_skipheadings menu_nounderline )
110 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
111 qw( title_left_image title_right_image
112 menu_top_image menu_body_image menu_bottom_image
115 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
116 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
117 qw( head body_header body_footer company_address ) ),
120 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
124 #{ %$skin_info_cache_agent };
125 $skin_info_cache_agent;
132 my $conf = new FS::Conf;
136 'phone_login' => $conf->exists('selfservice_server-phone_login'),
137 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
144 #false laziness w/FS::ClientAPI::passwd::passwd
148 my $conf = new FS::Conf;
151 if ( $p->{'domain'} eq 'svc_phone'
152 && $conf->exists('selfservice_server-phone_login') ) {
154 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
155 return { error => 'Number not found.' } unless $svc_phone;
158 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
159 #return { error => 'Only primary user may log in.' }
160 # if $conf->exists('selfservice_server-primary_only')
161 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
163 return { error => 'Incorrect PIN.' }
164 unless $svc_phone->check_pin($p->{'password'});
170 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
171 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
173 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
174 'domsvc' => $svc_domain->svcnum, }
176 return { error => 'User not found.' } unless $svc_acct;
178 if($conf->exists('selfservice_server-login_svcpart')) {
179 my @svcpart = $conf->config('selfservice_server-login_svcpart');
180 my $svcpart = $svc_acct->cust_svc->svcpart;
181 return { error => 'Invalid user.' }
182 unless grep($_ eq $svcpart, @svcpart);
185 return { error => 'Incorrect password.' }
186 unless $svc_acct->check_password($p->{'password'});
193 'svcnum' => $svc_x->svcnum,
196 my $cust_svc = $svc_x->cust_svc;
197 my $cust_pkg = $cust_svc->cust_pkg;
199 my $cust_main = $cust_pkg->cust_main;
200 $session->{'custnum'} = $cust_main->custnum;
201 if ( $conf->exists('pkg-balances') ) {
202 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
203 $cust_main->ncancelled_pkgs;
204 $session->{'pkgnum'} = $cust_pkg->pkgnum
205 if scalar(@cust_pkg) > 1;
209 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
210 #return { error => 'Only primary user may log in.' }
211 # if $conf->exists('selfservice_server-primary_only')
212 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
213 my $part_pkg = $cust_pkg->part_pkg;
214 return { error => 'Only primary user may log in.' }
215 if $conf->exists('selfservice_server-primary_only')
216 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
220 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
221 } until ( ! defined _cache->get($session_id) ); #just in case
223 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
224 _cache->set( $session_id, $session, $timeout );
226 return { 'error' => '',
227 'session_id' => $session_id,
233 if ( $p->{'session_id'} ) {
234 _cache->remove($p->{'session_id'});
235 return { %{ skin_info($p) }, 'error' => '' };
237 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
241 sub payment_gateway {
243 # takes a cust_main and a cust_payby entry, returns the payment_gateway
244 my $conf = new FS::Conf;
245 my $cust_main = shift;
246 my $cust_payby = shift;
247 my $gatewaynum = $conf->config('selfservice-payment_gateway');
249 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
250 die "configured gatewaynum $gatewaynum not found!" if !$pg;
254 return '' if ! FS::payby->realtime($cust_payby);
255 my $pg = $cust_main->agent->payment_gateway(
256 'method' => FS::payby->payby2bop($cust_payby),
266 my $conf = new FS::Conf;
268 my $info = skin_info($p);
270 use vars qw( $cust_paybys ); #cache for performance
271 unless ( $cust_paybys ) {
273 my %cust_paybys = map { $_ => 1 }
274 map { FS::payby->payby2payment($_) }
275 $conf->config('signup_server-payby');
277 $cust_paybys = [ keys %cust_paybys ];
280 $info->{'cust_paybys'} = $cust_paybys;
282 my($context, $session, $custnum) = _custoragent_session_custnum($p);
283 return { 'error' => $session } if $context eq 'error';
285 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
286 or return { 'error' => "unknown custnum $custnum" };
288 $info->{'hide_payment_fields'} = [
290 my $pg = payment_gateway($cust_main, $_);
291 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
292 } @{ $info->{cust_paybys} }
295 $info->{'self_suspend_reason'} =
296 $conf->config('selfservice-self_suspend_reason');
299 'custnum' => $custnum,
300 'access_pkgnum' => $session->{'pkgnum'},
301 'access_svcnum' => $session->{'svcnum'},
308 my($context, $session, $custnum) = _custoragent_session_custnum($p);
309 return { 'error' => $session } if $context eq 'error';
313 my $conf = new FS::Conf;
314 if ($conf->exists('cust_main-require_address2')) {
315 $return{'require_address2'} = '1';
317 $return{'require_address2'} = '';
320 if ( $custnum ) { #customer record
322 my $search = { 'custnum' => $custnum };
323 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
324 my $cust_main = qsearchs('cust_main', $search )
325 or return { 'error' => "unknown custnum $custnum" };
327 if ( $session->{'pkgnum'} ) {
328 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
330 $return{balance} = $cust_main->balance;
333 $return{tickets} = [ ($cust_main->tickets) ];
335 unless ( $session->{'pkgnum'} ) {
338 invnum => $_->invnum,
339 date => time2str("%b %o, %Y", $_->_date),
342 } $cust_main->open_cust_bill;
343 $return{open_invoices} = \@open;
346 $return{small_custview} =
347 small_custview( $cust_main,
348 scalar($conf->config('countrydefault')),
349 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
352 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
354 for (@cust_main_editable_fields) {
355 $return{$_} = $cust_main->get($_);
358 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
359 $return{payinfo} = $cust_main->paymask;
360 @return{'month', 'year'} = $cust_main->paydate_monthyear;
363 $return{'invoicing_list'} =
364 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
365 $return{'postal_invoicing'} =
366 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
368 if (scalar($conf->config('support_packages'))) {
369 my @support_services = ();
370 foreach ($cust_main->support_services) {
371 my $seconds = $_->svc_x->seconds;
372 my $time_remaining = (($seconds < 0) ? '-' : '' ).
373 int(abs($seconds)/3600)."h".
374 sprintf("%02d",(abs($seconds)%3600)/60)."m";
375 my $cust_pkg = $_->cust_pkg;
378 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
379 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
380 push @support_services, { svcnum => $_->svcnum,
381 time => $time_remaining,
386 $return{support_services} = \@support_services;
389 if ( $conf->config('prepayment_discounts-credit_type') ) {
391 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
394 } elsif ( $session->{'svcnum'} ) { #no customer record
396 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
397 or die "unknown svcnum";
398 $return{name} = $svc_acct->email;
402 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
406 return { 'error' => '',
407 'custnum' => $custnum,
415 my $session = _cache->get($p->{'session_id'})
416 or return { 'error' => "Can't resume session" }; #better error message
418 my $custnum = $session->{'custnum'}
419 or return { 'error' => "no customer record" };
421 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
422 or return { 'error' => "unknown custnum $custnum" };
424 my $new = new FS::cust_main { $cust_main->hash };
425 $new->set( $_ => $p->{$_} )
426 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
429 if (exists($p->{'payby'})) {
430 $p->{'payby'} =~ /^([A-Z]{4})$/
431 or return { 'error' => "illegal_payby " . $p->{'payby'} };
435 if ( $payby =~ /^(CARD|DCRD)$/ ) {
437 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
439 if ( $new->payinfo eq $cust_main->paymask ) {
440 $new->payinfo($cust_main->payinfo);
442 $new->payinfo($p->{'payinfo'});
445 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
447 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
450 $p->{'payinfo1'} =~ /^([\dx]+)$/
451 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
453 $p->{'payinfo2'} =~ /^([\dx]+)$/
454 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
456 $payinfo = $payinfo1. '@'. $payinfo2;
458 $new->payinfo( ($payinfo eq $cust_main->paymask)
459 ? $cust_main->payinfo
463 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
465 } elsif ( $payby =~ /^(BILL)$/ ) {
467 } elsif ( $payby ) { #notyet ready
468 return { 'error' => "unknown payby $payby" };
472 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
473 #false laziness with httemplate/edit/process/cust_main.cgi
474 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
475 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
477 @invoicing_list = $cust_main->invoicing_list;
480 my $error = $new->replace($cust_main, \@invoicing_list);
481 return { 'error' => $error } if $error;
484 return { 'error' => '' };
489 my $session = _cache->get($p->{'session_id'})
490 or return { 'error' => "Can't resume session" }; #better error message
496 my $conf = new FS::Conf;
497 use vars qw($payment_info); #cache for performance
498 unless ( $payment_info ) {
500 my %states = map { $_->state => 1 }
501 qsearch('cust_main_county', {
502 'country' => $conf->config('countrydefault') || 'US'
505 my %cust_paybys = map { $_ => 1 }
506 map { FS::payby->payby2payment($_) }
507 $conf->config('signup_server-payby');
509 my @cust_paybys = keys %cust_paybys;
513 #list all counties/states/countries
514 'cust_main_county' =>
515 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
517 #shortcut for one-country folks
519 [ sort { $a cmp $b } keys %states ],
521 'card_types' => card_types(),
523 'paytypes' => [ @FS::cust_main::paytypes ],
525 'paybys' => [ $conf->config('signup_server-payby') ],
526 'cust_paybys' => \@cust_paybys,
528 'stateid_label' => FS::Msgcat::_gettext('stateid'),
529 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
531 'show_ss' => $conf->exists('show_ss'),
532 'show_stateid' => $conf->exists('show_stateid'),
533 'show_paystate' => $conf->exists('show_bankstate'),
535 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
544 my %return = %$payment_info;
546 my $custnum = $session->{'custnum'};
548 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
549 or return { 'error' => "unknown custnum $custnum" };
551 $return{'hide_payment_fields'} = [
553 my $pg = payment_gateway($cust_main, $_);
554 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
555 } @{ $return{cust_paybys} }
558 $return{balance} = $cust_main->balance; #XXX pkg-balances?
560 $return{payname} = $cust_main->payname
561 || ( $cust_main->first. ' '. $cust_main->get('last') );
563 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
565 $return{payby} = $cust_main->payby;
566 $return{stateid_state} = $cust_main->stateid_state;
568 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
569 $return{card_type} = cardtype($cust_main->payinfo);
570 $return{payinfo} = $cust_main->paymask;
572 @return{'month', 'year'} = $cust_main->paydate_monthyear;
576 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
577 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
578 $return{payinfo1} = $payinfo1;
579 $return{payinfo2} = $payinfo2;
580 $return{paytype} = $cust_main->paytype;
581 $return{paystate} = $cust_main->paystate;
585 if ( $conf->config('prepayment_discounts-credit_type') ) {
587 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
590 #doubleclick protection
592 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
594 return { 'error' => '',
600 #some false laziness with httemplate/process/payment.cgi - look there for
601 #ACH and CVV support stuff
602 sub process_payment {
606 my $session = _cache->get($p->{'session_id'})
607 or return { 'error' => "Can't resume session" }; #better error message
611 my $custnum = $session->{'custnum'};
613 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
614 or return { 'error' => "unknown custnum $custnum" };
616 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
617 or return { 'error' => gettext('illegal_amount') };
619 return { error => 'Amount must be greater than 0' } unless $amount > 0;
621 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
622 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
623 my $discount_term = $1;
625 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
626 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
629 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
630 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
633 $p->{'payby'} ||= 'CARD';
634 $p->{'payby'} =~ /^([A-Z]{4})$/
635 or return { 'error' => "illegal_payby " . $p->{'payby'} };
638 #false laziness w/process/payment.cgi
642 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
644 $p->{'payinfo1'} =~ /^([\dx]+)$/
645 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
647 $p->{'payinfo2'} =~ /^([\dx]+)$/
648 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
650 $payinfo = $payinfo1. '@'. $payinfo2;
652 $payinfo = $cust_main->payinfo
653 if $cust_main->paymask eq $payinfo;
655 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
657 $payinfo = $p->{'payinfo'};
659 #more intelligent mathing will be needed here if you change
660 #card_masking_method and don't remove existing paymasks
661 $payinfo = $cust_main->payinfo
662 if $cust_main->paymask eq $payinfo;
665 $payinfo =~ /^(\d{13,16})$/
666 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
670 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
671 return { 'error' => gettext('unknown_card_type') }
672 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
674 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
675 if ( cardtype($payinfo) eq 'American Express card' ) {
676 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
677 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
680 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
681 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
687 die "unknown payby $payby";
691 'CARD' => [ qw( paystart_month paystart_year payissue payip
692 address1 address2 city state zip country ) ],
693 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
696 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
698 'payinfo' => $payinfo,
699 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
700 'payname' => $payname,
701 'paybatch' => $paybatch, #this doesn't actually do anything
703 'paynum_ref' => \$paynum,
704 'pkgnum' => $session->{'pkgnum'},
705 'discount_term' => $discount_term,
707 map { $_ => $p->{$_} } @{ $payby2fields{$payby} }
709 return { 'error' => $error } if $error;
711 $cust_main->apply_payments;
713 if ( $p->{'save'} ) {
714 my $new = new FS::cust_main { $cust_main->hash };
715 if ($payby eq 'CARD' || $payby eq 'DCRD') {
716 $new->set( $_ => $p->{$_} )
717 foreach qw( payname paystart_month paystart_year payissue payip
718 address1 address2 city state zip country );
719 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
720 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
721 $new->set( $_ => $p->{$_} )
722 foreach qw( payname payip paytype paystate
723 stateid stateid_state );
724 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
726 $new->set( 'payinfo' => $cust_main->card_token || $payinfo );
727 $new->set( 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01' );
728 my $error = $new->replace($cust_main);
730 #no, this causes customers to process their payments again
731 #return { 'error' => $error };
732 #XXX just warn verosely for now so i can figure out how these happen in
733 # the first place, eventually should redirect them to the "change
734 #address" page but indicate the payment did process??
735 delete($p->{'payinfo'}); #don't want to log this!
736 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
737 "NEW: ". Dumper($new)."\n".
738 "OLD: ". Dumper($cust_main)."\n".
739 "PACKET: ". Dumper($p)."\n";
746 my $receipt_html = '';
748 # currently supported for realtime CC only; send receipt data to SS
749 my $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
752 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
755 <TD ALIGN="right">Payment#</TD>
756 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
760 <TD ALIGN="right">Date</TD>
762 <TD BGCOLOR="#FFFFFF"><B>! .
763 time2str("%a %b %o, %Y %r", $cust_pay->_date)
769 <TD ALIGN="right">Amount</TD>
770 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paid . qq!</B></TD>
775 <TD ALIGN="right">Payment method</TD>
776 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
785 return { 'error' => '', 'receipt_html' => $receipt_html, };
789 sub realtime_collect {
792 my $session = _cache->get($p->{'session_id'})
793 or return { 'error' => "Can't resume session" }; #better error message
795 my $custnum = $session->{'custnum'};
797 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
798 or return { 'error' => "unknown custnum $custnum" };
801 if ( $p->{'amount'} ) {
802 $amount = $p->{'amount'};
804 elsif ( $session->{'pkgnum'} ) {
805 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
808 $amount = $cust_main->balance;
811 my $error = $cust_main->realtime_collect(
812 'method' => $p->{'method'},
814 'pkgnum' => $session->{'pkgnum'},
815 'session_id' => $p->{'session_id'},
819 return { 'error' => $error } unless ref( $error );
821 return { 'error' => '', amount => $amount, %$error };
824 sub process_payment_order_pkg {
827 my $hr = process_payment($p);
828 return $hr if $hr->{'error'};
833 sub process_payment_order_renew {
836 my $hr = process_payment($p);
837 return $hr if $hr->{'error'};
846 my $session = _cache->get($p->{'session_id'})
847 or return { 'error' => "Can't resume session" }; #better error message
851 my $custnum = $session->{'custnum'};
853 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
854 or return { 'error' => "unknown custnum $custnum" };
856 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
857 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
865 return { 'error' => $error } if $error;
867 return { 'error' => '',
869 'seconds' => $seconds,
870 'duration' => duration_exact($seconds),
871 'upbytes' => $upbytes,
872 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
873 'downbytes' => $downbytes,
874 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
875 'totalbytes'=> $totalbytes,
876 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
883 my $session = _cache->get($p->{'session_id'})
884 or return { 'error' => "Can't resume session" }; #better error message
886 my $custnum = $session->{'custnum'};
888 my $invnum = $p->{'invnum'};
890 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
891 'custnum' => $custnum } )
892 or return { 'error' => "Can't find invnum" };
896 return { 'error' => '',
898 'invoice_text' => join('', $cust_bill->print_text ),
899 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
907 #sessioning for this? how do we get the session id to the backend invoice
908 # template so it can add it to the link, blah
911 if ( $p->{'invnum'} ) {
912 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
913 or return { 'error' => 'unknown invnum' };
914 $agentnum = $cust_bill->cust_main->agentnum;
917 my $templatename = $p->{'template'} || $p->{'templatename'};
919 #false laziness-ish w/view/cust_bill-logo.cgi
921 my $conf = new FS::Conf;
922 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
923 $templatename = "_$1";
928 my $filename = "logo$templatename.png";
930 return { 'error' => '',
931 'logo' => $conf->config_binary($filename, $agentnum),
932 'content_type' => 'image/png', #should allow gif, jpg too
939 my $session = _cache->get($p->{'session_id'})
940 or return { 'error' => "Can't resume session" }; #better error message
942 my $custnum = $session->{'custnum'};
944 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
945 or return { 'error' => "unknown custnum $custnum" };
947 my @cust_bill = $cust_main->cust_bill;
949 return { 'error' => '',
950 'invoices' => [ map { { 'invnum' => $_->invnum,
951 '_date' => $_->_date,
952 'date' => time2str("%b %o, %Y", $_->_date),
961 my $session = _cache->get($p->{'session_id'})
962 or return { 'error' => "Can't resume session" }; #better error message
964 my $custnum = $session->{'custnum'};
966 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
967 or return { 'error' => "unknown custnum $custnum" };
969 my @errors = $cust_main->cancel( 'quiet'=>1 );
971 my $error = scalar(@errors) ? join(' / ', @errors) : '';
973 return { 'error' => $error };
980 my($context, $session, $custnum) = _custoragent_session_custnum($p);
981 return { 'error' => $session } if $context eq 'error';
983 my $search = { 'custnum' => $custnum };
984 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
985 my $cust_main = qsearchs('cust_main', $search )
986 or return { 'error' => "unknown custnum $custnum" };
988 my $conf = new FS::Conf;
990 # the duplication below is necessary:
991 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
992 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
993 # non-backwards-compatible change breaking the software of anyone using the API
994 # instead of the stock selfservice
995 # 2. to return cancelled packages as well - for wholesale and non-wholesale
996 if( $conf->exists('selfservice_server-view-wholesale') ) {
997 return { 'svcnum' => $session->{'svcnum'},
998 'custnum' => $custnum,
999 'cust_pkg' => [ map {
1001 part_pkg => [ map $_->hashref, $_->part_pkg ],
1003 [ map $_->hashref, $_->available_part_svc ],
1005 [ map { my $ref = { $_->hash,
1006 label => [ $_->label ],
1008 $ref->{_password} = $_->svc_x->_password
1009 if $context eq 'agent'
1010 && $conf->exists('agent-showpasswords')
1011 && $_->part_svc->svcdb eq 'svc_acct';
1016 } $cust_main->cust_pkg
1019 small_custview( $cust_main, $conf->config('countrydefault') ),
1020 'wholesale_view' => 1,
1021 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1022 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1023 'lnp' => $conf->exists('svc_phone-lnp'),
1027 { 'svcnum' => $session->{'svcnum'},
1028 'custnum' => $custnum,
1029 'cust_pkg' => [ map {
1033 [ map $_->hashref, $_->available_part_svc ],
1035 [ map { my $ref = { $_->hash,
1036 label => [ $_->label ],
1038 $ref->{_password} = $_->svc_x->_password
1039 if $context eq 'agent'
1040 && $conf->exists('agent-showpasswords')
1041 && $_->part_svc->svcdb eq 'svc_acct';
1042 $ref->{svchash} = { $_->svc_x->hash } if
1043 $_->part_svc->svcdb eq 'svc_phone';
1044 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1045 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1050 } $cust_main->ncancelled_pkgs
1053 small_custview( $cust_main, $conf->config('countrydefault') ),
1061 my $conf = new FS::Conf;
1063 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1064 return { 'error' => $session } if $context eq 'error';
1066 my $search = { 'custnum' => $custnum };
1067 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1068 my $cust_main = qsearchs('cust_main', $search )
1069 or return { 'error' => "unknown custnum $custnum" };
1072 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1073 foreach my $cust_pkg ( $p->{'ncancelled'}
1074 ? $cust_main->ncancelled_pkgs
1075 : $cust_main->unsuspended_pkgs ) {
1076 next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1077 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1079 if ( $p->{'svcdb'} ) {
1080 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1082 : ref($p->{'svcdb'}) eq 'ARRAY'
1083 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1084 : { $p->{'svcdb'} => 1 };
1085 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1088 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1092 'svcnum' => $session->{'svcnum'},
1093 'custnum' => $custnum,
1094 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1097 my $svc_x = $_->svc_x;
1098 my($label, $value) = $_->label;
1099 my $svcdb = $_->part_svc->svcdb;
1100 my $part_pkg = $_->cust_pkg->part_pkg;
1103 'svcnum' => $_->svcnum,
1109 if ( $svcdb eq 'svc_acct' ) {
1112 'username' => $svc_x->username,
1113 'email' => $svc_x->email,
1114 'seconds' => $svc_x->seconds,
1115 'upbytes' => display_bytecount($svc_x->upbytes),
1116 'downbytes' => display_bytecount($svc_x->downbytes),
1117 'totalbytes' => display_bytecount($svc_x->totalbytes),
1119 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1120 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1121 'recharge_upbytes' =>
1122 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1123 'recharge_downbytes' =>
1124 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1125 'recharge_totalbytes' =>
1126 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1130 } elsif ( $svcdb eq 'svc_phone' ) {
1144 sub _list_svc_usage {
1145 my($svc_acct, $begin, $end) = @_;
1147 foreach my $part_export (
1148 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1149 qw( sqlradius sqlradius_withdomain )
1151 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1156 sub list_svc_usage {
1157 _usage_details(\&_list_svc_usage, @_);
1160 sub _list_support_usage {
1161 my($svc_acct, $begin, $end) = @_;
1163 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1164 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1166 push @usage, { 'seconds' => $_->seconds,
1167 'support' => $_->support,
1168 '_date' => $_->_date,
1169 'id' => $_->transaction_id,
1170 'creator' => $_->creator,
1171 'subject' => $_->subject,
1172 'status' => $_->status,
1173 'ticketid' => $_->ticketid,
1179 sub list_support_usage {
1180 _usage_details(\&_list_support_usage, @_);
1183 sub _list_cdr_usage {
1184 my($svc_phone, $begin, $end) = @_;
1185 map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1186 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1189 sub list_cdr_usage {
1191 _usage_details( \&_list_cdr_usage, $p,
1192 'svcdb' => 'svc_phone',
1196 sub _usage_details {
1197 my($callback, $p, %opt) = @_;
1199 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1200 return { 'error' => $session } if $context eq 'error';
1202 my $search = { 'svcnum' => $p->{'svcnum'} };
1203 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1205 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1207 my $svc_x = qsearchs( $svcdb, $search );
1208 return { 'error' => 'No service selected in list_svc_usage' }
1211 my $header = $svcdb eq 'svc_phone'
1212 ? [ split(',', FS::cdr::invoice_header('default') ) ] #XXX
1215 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1216 my $freq = $cust_pkg->part_pkg->freq;
1217 my $start = $cust_pkg->setup;
1218 #my $end = $cust_pkg->bill; # or time?
1221 unless ( $p->{beginning} ) {
1222 $p->{beginning} = $cust_pkg->last_bill;
1223 $p->{ending} = $end;
1226 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1228 #kinda false laziness with FS::cust_main::bill, but perhaps
1229 #we should really change this bit to DateTime and DateTime::Duration
1231 #change this bit to use Date::Manip? CAREFUL with timezones (see
1232 # mailing list archive)
1233 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1234 (localtime($p->{ending}) )[0,1,2,3,4,5];
1235 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1236 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1238 if ( $freq =~ /^\d+$/ ) {
1240 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1242 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1243 } elsif ( $freq =~ /^(\d+)w$/ ) {
1245 $nmday += $weeks * 7;
1246 $pmday -= $weeks * 7;
1247 } elsif ( $freq =~ /^(\d+)d$/ ) {
1251 } elsif ( $freq =~ /^(\d+)h$/ ) {
1256 return { 'error' => "unparsable frequency: ". $freq };
1259 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1260 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1264 'svcnum' => $p->{svcnum},
1265 'beginning' => $p->{beginning},
1266 'ending' => $p->{ending},
1267 'previous' => ($previous > $start) ? $previous : $start,
1268 'next' => ($next < $end) ? $next : $end,
1269 'header' => $header,
1277 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1278 return { 'error' => $session } if $context eq 'error';
1280 my $search = { 'custnum' => $custnum };
1281 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1282 my $cust_main = qsearchs('cust_main', $search )
1283 or return { 'error' => "unknown custnum $custnum" };
1285 my $status = $cust_main->status;
1286 #false laziness w/ClientAPI/Signup.pm
1288 my $cust_pkg = new FS::cust_pkg ( {
1289 'custnum' => $custnum,
1290 'pkgpart' => $p->{'pkgpart'},
1292 my $error = $cust_pkg->check;
1293 return { 'error' => $error } if $error;
1296 unless ( $p->{'svcpart'} eq 'none' ) {
1300 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1302 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1303 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1304 $svcdb = $part_svc->svcdb;
1306 $svcdb = 'svc_acct';
1308 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1311 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
1312 'svc_domain' => [ qw( domain ) ],
1313 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
1314 'svc_external' => [ qw( id title ) ],
1315 'svc_pbx' => [ qw( id name ) ],
1318 my $svc_x = "FS::$svcdb"->new( {
1319 'svcpart' => $svcpart,
1320 map { $_ => $p->{$_} } @{$fields{$svcdb}}
1323 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1326 while ( length($p->{"snarf_machine$snarfnum"}) ) {
1327 my $acct_snarf = new FS::acct_snarf ( {
1328 'machine' => $p->{"snarf_machine$snarfnum"},
1329 'protocol' => $p->{"snarf_protocol$snarfnum"},
1330 'username' => $p->{"snarf_username$snarfnum"},
1331 '_password' => $p->{"snarf_password$snarfnum"},
1334 push @acct_snarf, $acct_snarf;
1336 $svc_x->child_objects( \@acct_snarf );
1339 my $y = $svc_x->setdefault; # arguably should be in new method
1340 return { 'error' => $y } if $y && !ref($y);
1342 $error = $svc_x->check;
1343 return { 'error' => $error } if $error;
1350 tie my %hash, 'Tie::RefHash';
1351 %hash = ( $cust_pkg => \@svc );
1353 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1354 return { 'error' => $error } if $error;
1356 my $conf = new FS::Conf;
1357 if ( $conf->exists('signup_server-realtime') ) {
1359 my $bill_error = _do_bop_realtime( $cust_main, $status );
1362 $cust_pkg->cancel('quiet'=>1);
1365 $cust_pkg->reexport;
1369 $cust_pkg->reexport;
1372 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1374 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1381 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1382 return { 'error' => $session } if $context eq 'error';
1384 my $search = { 'custnum' => $custnum };
1385 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1386 my $cust_main = qsearchs('cust_main', $search )
1387 or return { 'error' => "unknown custnum $custnum" };
1389 my $status = $cust_main->status;
1390 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1391 or return { 'error' => "unknown package $p->{pkgnum}" };
1394 my $error = FS::cust_pkg::order( $custnum,
1400 my $conf = new FS::Conf;
1401 if ( $conf->exists('signup_server-realtime') ) {
1403 my $bill_error = _do_bop_realtime( $cust_main, $status );
1406 $newpkg[0]->suspend;
1409 $newpkg[0]->reexport;
1413 $newpkg[0]->reexport;
1416 return { error => '', pkgnum => $cust_pkg->pkgnum };
1420 sub order_recharge {
1423 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1424 return { 'error' => $session } if $context eq 'error';
1426 my $search = { 'custnum' => $custnum };
1427 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1428 my $cust_main = qsearchs('cust_main', $search )
1429 or return { 'error' => "unknown custnum $custnum" };
1431 my $status = $cust_main->status;
1432 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1433 or return { 'error' => "unknown service " . $p->{'svcnum'} };
1435 my $svc_x = $cust_svc->svc_x;
1436 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1439 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
1440 qw ( recharge_seconds recharge_upbytes recharge_downbytes
1441 recharge_totalbytes );
1442 my $amount = $part_pkg->option('recharge_amount', 1);
1444 my ($l, $v, $d) = $cust_svc->label; # blah
1445 my $pkg = "Recharge $v";
1447 my $bill_error = $cust_main->charge($amount, $pkg,
1448 "time: $vhash{seconds}, up: $vhash{upbytes}," .
1449 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1450 $part_pkg->taxclass); #meh
1452 my $conf = new FS::Conf;
1453 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1455 $bill_error = _do_bop_realtime( $cust_main, $status );
1460 my $error = $svc_x->recharge (\%vhash);
1461 return { 'error' => $error } if $error;
1465 my $error = $bill_error;
1466 $error ||= $svc_x->recharge (\%vhash);
1467 return { 'error' => $error } if $error;
1470 return { error => '', svc => $cust_svc->part_svc->svc };
1474 sub _do_bop_realtime {
1475 my ($cust_main, $status) = (shift, shift);
1477 my $old_balance = $cust_main->balance;
1479 my $bill_error = $cust_main->bill
1480 || $cust_main->apply_payments_and_credits
1481 || $cust_main->realtime_collect('selfservice' => 1);
1483 if ( $cust_main->balance > $old_balance
1484 && $cust_main->balance > 0
1485 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1486 1 : $status eq 'suspended' ) ) {
1487 #this makes sense. credit is "un-doing" the invoice
1488 my $conf = new FS::Conf;
1489 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1490 'self-service decline',
1491 'reason_type' => $conf->config('signup_credit_type'),
1493 $cust_main->apply_credits( 'order' => 'newest' );
1495 return { 'error' => '_decline', 'bill_error' => $bill_error };
1504 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1505 return { 'error' => $session } if $context eq 'error';
1507 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1508 or return { 'error' => "unknown custnum $custnum" };
1510 my @cust_pkg = sort { $a->bill <=> $b->bill }
1511 grep { $_->part_pkg->freq ne '0' }
1512 $cust_main->ncancelled_pkgs;
1514 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1516 my $total = $cust_main->balance;
1519 my $bill = $_->bill;
1520 $total += $_->part_pkg->base_recur($_, \$bill);
1521 my $renew_date = $_->part_pkg->add_freq($_->bill);
1523 'pkgnum' => $_->pkgnum,
1524 'amount' => sprintf('%.2f', $total),
1525 'bill_date' => $_->bill,
1526 'bill_date_pretty' => time2str('%x', $_->bill),
1527 'renew_date' => $renew_date,
1528 'renew_date_pretty' => time2str('%x', $renew_date),
1529 'expire_date' => $_->expire,
1530 'expire_date_pretty' => time2str('%x', $_->expire),
1535 return { 'dates' => \@array };
1539 sub payment_info_renew_info {
1541 my $renew_info = renew_info($p);
1542 my $payment_info = payment_info($p);
1543 return { %$renew_info,
1551 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1552 return { 'error' => $session } if $context eq 'error';
1554 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1555 or return { 'error' => "unknown custnum $custnum" };
1557 my $date = $p->{'date'};
1561 #freeside-daily -n -d $date fs_daily $custnum
1562 $cust_main->bill_and_collect( 'time' => $date,
1563 'invoice_time' => $now,
1564 'actual_time' => $now,
1565 'check_freq' => '1d',
1568 return { 'error' => '' };
1572 # these are basically the same
1573 sub cancel_pkg { alter_pkg(shift, 'cancel', 'quiet' => 1) }
1575 my $conf = new FS::Conf;
1576 my $reasonnum = $conf->config('selfservice-self_suspend_reason')
1577 or return { 'error' => "Permission denied" };
1578 alter_pkg(shift, 'suspend', 'reason' => $reasonnum)
1584 my $session = _cache->get($p->{'session_id'})
1585 or return { 'error' => "Can't resume session" }; #better error message
1587 my $custnum = $session->{'custnum'};
1589 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1590 or return { 'error' => "unknown custnum $custnum" };
1592 my $pkgnum = $p->{'pkgnum'};
1594 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1595 'pkgnum' => $pkgnum, } )
1596 or return { 'error' => "unknown pkgnum $pkgnum" };
1598 my $error = $cust_pkg->$method(@_);
1599 return { 'error' => $error };
1603 sub provision_phone {
1606 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1608 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1609 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1610 return { 'error' => $session } if $context eq 'error';
1612 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1613 return { 'error' => 'service not found' } unless $svc_phone;
1614 return { 'error' => 'invalid svcnum' }
1615 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1617 $svc_phone->email($p->{'email'})
1618 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1619 $svc_phone->forwarddst($p->{'forwarddst'})
1620 if $svc_phone->forwarddst ne $p->{'forwarddst'}
1621 && $p->{'forwarddst'} =~ /^(\d+|)$/;
1622 return { 'error' => $svc_phone->replace };
1626 unless($p->{'lnp'}) {
1627 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1628 $p->{'lnp_status'} = "portingin";
1629 return _provision( 'FS::svc_phone',
1630 [qw(lnp_desired_due_date lnp_other_provider
1631 lnp_other_provider_account phonenum countrycode lnp_status)],
1632 [qw(phonenum countrycode)],
1639 unless (scalar(@bulkdid)) {
1640 return _provision( 'FS::svc_phone',
1641 [qw(phonenum countrycode)],
1642 [qw(phonenum countrycode)],
1648 # bulk DID order case
1650 foreach my $did ( @bulkdid ) {
1651 $did =~ s/[^0-9]//g;
1652 $error = _provision( 'FS::svc_phone',
1653 [qw(phonenum countrycode)],
1654 [qw(phonenum countrycode)],
1656 'pkgnum' => $p->{'pkgnum'},
1657 'svcpart' => $p->{'svcpart'},
1659 'countrycode' => $p->{'countrycode'},
1660 'session_id' => $p->{'session_id'},
1663 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1665 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1668 sub provision_acct {
1670 warn "provision_acct called\n"
1673 return { 'error' => gettext('passwords_dont_match') }
1674 if $p->{'_password'} ne $p->{'_password2'};
1675 return { 'error' => gettext('empty_password') }
1676 unless length($p->{'_password'});
1678 if ($p->{'domsvc'}) {
1679 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1680 qw ( svcpart pkgnum ) );
1681 return { 'error' => gettext('invalid_domain') }
1682 unless ($domains{$p->{'domsvc'}});
1685 warn "provision_acct calling _provision\n"
1687 _provision( 'FS::svc_acct',
1688 [qw(username _password domsvc)],
1689 [qw(username _password domsvc)],
1695 sub provision_external {
1697 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1698 _provision( 'FS::svc_external',
1707 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1708 warn "_provision called for $class\n"
1711 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1712 return { 'error' => $session } if $context eq 'error';
1714 my $search = { 'custnum' => $custnum };
1715 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1716 my $cust_main = qsearchs('cust_main', $search )
1717 or return { 'error' => "unknown custnum $custnum" };
1719 my $pkgnum = $p->{'pkgnum'};
1721 warn "searching for custnum $custnum pkgnum $pkgnum\n"
1723 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1724 'pkgnum' => $pkgnum,
1726 or return { 'error' => "unknown pkgnum $pkgnum" };
1728 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1730 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1731 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1733 warn "creating $class record\n"
1735 my $svc_x = $class->new( {
1736 'pkgnum' => $p->{'pkgnum'},
1737 'svcpart' => $p->{'svcpart'},
1738 map { $_ => $p->{$_} } @$fields
1740 warn "inserting $class record\n"
1742 my $error = $svc_x->insert;
1745 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1747 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1750 my $return = { 'svc' => $part_svc->svc,
1752 map { $_ => $svc_x->get($_) } @$return_fields
1754 warn "_provision returning ". Dumper($return). "\n"
1763 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1764 return { 'error' => $session } if $context eq 'error';
1766 my $search = { 'custnum' => $custnum };
1767 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1768 my $cust_main = qsearchs('cust_main', $search )
1769 or return { 'error' => "unknown custnum $custnum" };
1771 my $pkgnum = $p->{'pkgnum'};
1773 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1774 'pkgnum' => $pkgnum,
1776 or return { 'error' => "unknown pkgnum $pkgnum" };
1778 my $svcpart = $p->{'svcpart'};
1780 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1781 'svcpart' => $svcpart, } )
1782 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1783 my $part_svc = $pkg_svc->part_svc;
1785 my $conf = new FS::Conf;
1788 'svc' => $part_svc->svc,
1789 'svcdb' => $part_svc->svcdb,
1790 'pkgnum' => $pkgnum,
1791 'svcpart' => $svcpart,
1792 'custnum' => $custnum,
1794 'security_phrase' => 0, #XXX !
1795 'svc_acct_pop' => [], #XXX !
1797 'init_popstate' => '',
1802 small_custview( $cust_main, $conf->config('countrydefault') ),
1806 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
1807 && $ret->{'svcdb'} eq 'svc_phone') {
1808 $ret->{'svcnum'} = $p->{'svcnum'};
1809 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1810 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
1811 $ret->{'email'} = $svc_phone->email;
1812 $ret->{'forwarddst'} = $svc_phone->forwarddst;
1819 sub unprovision_svc {
1822 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1823 return { 'error' => $session } if $context eq 'error';
1825 my $search = { 'custnum' => $custnum };
1826 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1827 my $cust_main = qsearchs('cust_main', $search )
1828 or return { 'error' => "unknown custnum $custnum" };
1830 my $svcnum = $p->{'svcnum'};
1832 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
1833 or return { 'error' => "unknown svcnum $svcnum" };
1835 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1836 unless $cust_svc->cust_pkg->custnum == $custnum;
1838 my $conf = new FS::Conf;
1840 return { 'svc' => $cust_svc->part_svc->svc,
1841 'error' => $cust_svc->cancel,
1843 small_custview( $cust_main, $conf->config('countrydefault') ),
1848 sub myaccount_passwd {
1850 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1851 return { 'error' => $session } if $context eq 'error';
1853 return { 'error' => "New passwords don't match." }
1854 if $p->{'new_password'} ne $p->{'new_password2'};
1856 return { 'error' => 'Enter new password' }
1857 unless length($p->{'new_password'});
1859 #my $search = { 'custnum' => $custnum };
1860 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1861 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1862 my $search = " AND custnum = $1";
1863 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1865 my $svc_acct = qsearchs( {
1866 'table' => 'svc_acct',
1867 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1868 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
1869 'LEFT JOIN cust_main USING ( custnum ) ',
1870 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
1871 'extra_sql' => $search, #important
1873 or return { 'error' => "Service not found" };
1875 $svc_acct->_password($p->{'new_password'});
1876 my $error = $svc_acct->replace();
1878 my($label, $value) = $svc_acct->cust_svc->label;
1880 return { 'error' => $error,
1889 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1890 return { 'error' => $session } if $context eq 'error';
1892 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
1893 FS::TicketSystem->init();
1895 my $conf = new FS::Conf;
1896 my $queue = $p->{'queue'}
1897 || $conf->config('ticket_system-selfservice_queueid')
1898 || $conf->config('ticket_system-default_queueid');
1900 warn "$me create_ticket: creating ticket\n" if $DEBUG;
1901 my $err_or_ticket = FS::TicketSystem->create_ticket(
1902 '', #create RT session based on FS CurrentUser (fs_selfservice)
1904 'custnum' => $custnum,
1905 'svcnum' => $session->{'svcnum'},
1906 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
1909 if ( ref($err_or_ticket) ) {
1910 warn "$me create_ticket: sucessful: ". $err_or_ticket->id. "\n"
1912 return { 'error' => '',
1913 'ticket_id' => $err_or_ticket->id,
1916 warn "$me create_ticket: unsucessful: $err_or_ticket\n"
1918 return { 'error' => $err_or_ticket };
1926 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1927 return { 'error' => $session } if $context eq 'error';
1929 return { error => 'requested format not implemented' }
1930 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
1932 my $conf = new FS::Conf;
1933 my $age_threshold = 0;
1934 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
1935 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
1937 my $search = { 'custnum' => $custnum };
1938 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1939 my $cust_main = qsearchs('cust_main', $search )
1940 or return { 'error' => "unknown custnum $custnum" };
1942 # does it make more sense to just run one sql query for this instead of all the
1943 # insanity below? would increase performance greately for large data sets?
1945 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1946 my @part_svc = $cust_pkg->part_svc;
1947 foreach my $part_svc ( @part_svc ) {
1948 if($part_svc->svcdb eq 'svc_phone'){
1949 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
1950 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
1951 push @svc_phone, $cust_pkg_svc->svc_x
1952 if $cust_pkg_svc->date_inserted >= $age_threshold;
1960 my($xls_r,$xls_c) = (0,0);
1963 my @fields = qw( countrycode phonenum pin sip_password phone_name );
1964 if($p->{'format'} eq 'csv') {
1965 $csv = new Text::CSV_XS { 'always_quote' => 1,
1968 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
1969 $content .= $csv->string;
1971 elsif($p->{'format'} eq 'xls') {
1972 my $XLS1 = new IO::Scalar \$content;
1973 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
1974 or return { 'error' => "Error opening .xls file: $!" };
1975 $xls = $xls_workbook->add_worksheet('DIDs');
1976 foreach ( @fields ) {
1977 $xls->write(0,$xls_c++,$_);
1982 foreach my $svc_phone ( @svc_phone ) {
1983 my @cols = map { $svc_phone->$_ } @fields;
1984 if($p->{'format'} eq 'csv') {
1985 return { 'error' => 'Unable to create CSV' }
1986 unless $csv->combine(@cols);
1987 $content .= $csv->string;
1989 elsif($p->{'format'} eq 'xls') {
1992 $xls->write($xls_r,$xls_c++,$_);
1998 $xls_workbook->close() if $p->{'format'} eq 'xls';
2000 { content => $content, format => $p->{'format'}, };
2005 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2006 return { 'error' => $session } if $context eq 'error';
2008 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2009 FS::TicketSystem->init();
2011 if(length($p->{'reply'})) {
2012 # currently this allows anyone to correspond on any ticket as fs_selfservice
2014 my @err_or_res = FS::TicketSystem->correspond_ticket(
2015 '', #create RT session based on FS CurrentUser (fs_selfservice)
2016 'ticket_id' => $p->{'ticket_id'},
2017 'content' => $p->{'reply'},
2020 return { 'error' => 'unable to reply to ticket' }
2021 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2024 warn "$me get_ticket: getting ticket\n" if $DEBUG;
2025 my $err_or_ticket = FS::TicketSystem->get_ticket(
2026 '', #create RT session based on FS CurrentUser (fs_selfservice)
2027 'ticket_id' => $p->{'ticket_id'},
2030 if ( ref($err_or_ticket) ) {
2032 # since we're bypassing the RT security/permissions model by always using
2033 # fs_selfservice as the RT user (as opposed to a requestor, which we
2034 # can't do since we want all tickets linked to a cust), we check below whether
2035 # the requested ticket was actually linked to this customer
2036 my @custs = @{$err_or_ticket->{'custs'}};
2037 my @txns = @{$err_or_ticket->{'txns'}};
2040 return { 'error' => 'no customer' } unless ( $custnum && scalar(@custs) );
2042 return { 'error' => 'invalid ticket requested' }
2043 unless grep($_ eq $custnum, @custs);
2045 foreach my $txn ( @txns ) {
2046 push @filtered_txns, $txn
2047 if ($txn->{'type'} eq 'EmailRecord'
2048 || $txn->{'type'} eq 'Correspond'
2049 || $txn->{'type'} eq 'Create');
2052 warn "$me get_ticket: sucessful: \n"
2054 return { 'error' => '',
2055 'transactions' => \@filtered_txns,
2056 'ticket_id' => $p->{'ticket_id'},
2059 warn "$me create_ticket: unsucessful: $err_or_ticket\n"
2061 return { 'error' => $err_or_ticket };
2068 sub _custoragent_session_custnum {
2071 my($context, $session, $custnum);
2072 if ( $p->{'session_id'} ) {
2074 $context = 'customer';
2075 $session = _cache->get($p->{'session_id'})
2076 or return ( 'error' => "Can't resume session" ); #better error message
2077 $custnum = $session->{'custnum'};
2079 } elsif ( $p->{'agent_session_id'} ) {
2082 my $agent_cache = new FS::ClientAPI_SessionCache( {
2083 'namespace' => 'FS::ClientAPI::Agent',
2085 $session = $agent_cache->get($p->{'agent_session_id'})
2086 or return ( 'error' => "Can't resume session" ); #better error message
2087 $custnum = $p->{'custnum'};
2091 return ( 'error' => "Can't resume session" ); #better error message
2094 ($context, $session, $custnum);