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 ( defined($p->{'agentnum'}) and $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 date_format ) ),
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', $cust_main->agentnum);
298 $info->{'edit_ticket_subject'} =
299 $conf->exists('ticket_system-selfservice_edit_subject') &&
300 $cust_main->edit_subject;
303 'custnum' => $custnum,
304 'access_pkgnum' => $session->{'pkgnum'},
305 'access_svcnum' => $session->{'svcnum'},
312 my($context, $session, $custnum) = _custoragent_session_custnum($p);
313 return { 'error' => $session } if $context eq 'error';
317 my $conf = new FS::Conf;
318 if ($conf->exists('cust_main-require_address2')) {
319 $return{'require_address2'} = '1';
321 $return{'require_address2'} = '';
324 if ( $FS::TicketSystem::system ) {
325 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
326 FS::TicketSystem->init();
329 if ( $custnum ) { #customer record
331 my $search = { 'custnum' => $custnum };
332 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
333 my $cust_main = qsearchs('cust_main', $search )
334 or return { 'error' => "unknown custnum $custnum" };
336 if ( $session->{'pkgnum'} ) {
337 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
339 $return{balance} = $cust_main->balance;
342 $return{tickets} = [ ($cust_main->tickets) ];
344 unless ( $session->{'pkgnum'} ) {
347 invnum => $_->invnum,
348 date => time2str("%b %o, %Y", $_->_date),
351 } $cust_main->open_cust_bill;
352 $return{open_invoices} = \@open;
355 $return{small_custview} =
356 small_custview( $cust_main,
357 scalar($conf->config('countrydefault')),
358 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
361 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
363 for (@cust_main_editable_fields) {
364 $return{$_} = $cust_main->get($_);
367 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
368 $return{payinfo} = $cust_main->paymask;
369 @return{'month', 'year'} = $cust_main->paydate_monthyear;
372 $return{'invoicing_list'} =
373 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
374 $return{'postal_invoicing'} =
375 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
377 if (scalar($conf->config('support_packages'))) {
378 my @support_services = ();
379 foreach ($cust_main->support_services) {
380 my $seconds = $_->svc_x->seconds;
381 my $time_remaining = (($seconds < 0) ? '-' : '' ).
382 int(abs($seconds)/3600)."h".
383 sprintf("%02d",(abs($seconds)%3600)/60)."m";
384 my $cust_pkg = $_->cust_pkg;
387 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
388 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
389 push @support_services, { svcnum => $_->svcnum,
390 time => $time_remaining,
395 $return{support_services} = \@support_services;
398 if ( $conf->config('prepayment_discounts-credit_type') ) {
400 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
403 } elsif ( $session->{'svcnum'} ) { #no customer record
405 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
406 or die "unknown svcnum";
407 $return{name} = $svc_acct->email;
411 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
415 return { 'error' => '',
416 'custnum' => $custnum,
424 my $session = _cache->get($p->{'session_id'})
425 or return { 'error' => "Can't resume session" }; #better error message
427 my $custnum = $session->{'custnum'}
428 or return { 'error' => "no customer record" };
430 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
431 or return { 'error' => "unknown custnum $custnum" };
433 my $new = new FS::cust_main { $cust_main->hash };
434 $new->set( $_ => $p->{$_} )
435 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
438 if (exists($p->{'payby'})) {
439 $p->{'payby'} =~ /^([A-Z]{4})$/
440 or return { 'error' => "illegal_payby " . $p->{'payby'} };
444 if ( $payby =~ /^(CARD|DCRD)$/ ) {
446 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
448 if ( $new->payinfo eq $cust_main->paymask ) {
449 $new->payinfo($cust_main->payinfo);
451 $new->payinfo($p->{'payinfo'});
454 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
456 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
459 $p->{'payinfo1'} =~ /^([\dx]+)$/
460 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
462 $p->{'payinfo2'} =~ /^([\dx]+)$/
463 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
465 $payinfo = $payinfo1. '@'. $payinfo2;
467 $new->payinfo( ($payinfo eq $cust_main->paymask)
468 ? $cust_main->payinfo
472 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
474 } elsif ( $payby =~ /^(BILL)$/ ) {
476 } elsif ( $payby ) { #notyet ready
477 return { 'error' => "unknown payby $payby" };
481 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
482 #false laziness with httemplate/edit/process/cust_main.cgi
483 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
484 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
486 @invoicing_list = $cust_main->invoicing_list;
489 my $error = $new->replace($cust_main, \@invoicing_list);
490 return { 'error' => $error } if $error;
493 return { 'error' => '' };
498 my $session = _cache->get($p->{'session_id'})
499 or return { 'error' => "Can't resume session" }; #better error message
505 my $conf = new FS::Conf;
506 use vars qw($payment_info); #cache for performance
507 unless ( $payment_info ) {
509 my %states = map { $_->state => 1 }
510 qsearch('cust_main_county', {
511 'country' => $conf->config('countrydefault') || 'US'
514 my %cust_paybys = map { $_ => 1 }
515 map { FS::payby->payby2payment($_) }
516 $conf->config('signup_server-payby');
518 my @cust_paybys = keys %cust_paybys;
522 #list all counties/states/countries
523 'cust_main_county' =>
524 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
526 #shortcut for one-country folks
528 [ sort { $a cmp $b } keys %states ],
530 'card_types' => card_types(),
532 'paytypes' => [ @FS::cust_main::paytypes ],
534 'paybys' => [ $conf->config('signup_server-payby') ],
535 'cust_paybys' => \@cust_paybys,
537 'stateid_label' => FS::Msgcat::_gettext('stateid'),
538 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
540 'show_ss' => $conf->exists('show_ss'),
541 'show_stateid' => $conf->exists('show_stateid'),
542 'show_paystate' => $conf->exists('show_bankstate'),
544 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
546 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
555 my %return = %$payment_info;
557 my $custnum = $session->{'custnum'};
559 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
560 or return { 'error' => "unknown custnum $custnum" };
562 $return{'hide_payment_fields'} = [
564 my $pg = payment_gateway($cust_main, $_);
565 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
566 } @{ $return{cust_paybys} }
569 $return{balance} = $cust_main->balance; #XXX pkg-balances?
571 $return{payname} = $cust_main->payname
572 || ( $cust_main->first. ' '. $cust_main->get('last') );
574 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
576 $return{payby} = $cust_main->payby;
577 $return{stateid_state} = $cust_main->stateid_state;
579 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
580 $return{card_type} = cardtype($cust_main->payinfo);
581 $return{payinfo} = $cust_main->paymask;
583 @return{'month', 'year'} = $cust_main->paydate_monthyear;
587 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
588 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
589 $return{payinfo1} = $payinfo1;
590 $return{payinfo2} = $payinfo2;
591 $return{paytype} = $cust_main->paytype;
592 $return{paystate} = $cust_main->paystate;
596 if ( $conf->config('prepayment_discounts-credit_type') ) {
598 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
601 #doubleclick protection
603 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
605 return { 'error' => '',
611 #some false laziness with httemplate/process/payment.cgi - look there for
612 #ACH and CVV support stuff
613 sub process_payment {
617 my $session = _cache->get($p->{'session_id'})
618 or return { 'error' => "Can't resume session" }; #better error message
622 my $custnum = $session->{'custnum'};
624 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
625 or return { 'error' => "unknown custnum $custnum" };
627 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
628 or return { 'error' => gettext('illegal_amount') };
630 return { error => 'Amount must be greater than 0' } unless $amount > 0;
632 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
633 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
634 my $discount_term = $1;
636 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
637 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
640 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
641 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
644 $p->{'payby'} ||= 'CARD';
645 $p->{'payby'} =~ /^([A-Z]{4})$/
646 or return { 'error' => "illegal_payby " . $p->{'payby'} };
649 #false laziness w/process/payment.cgi
653 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
655 $p->{'payinfo1'} =~ /^([\dx]+)$/
656 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
658 $p->{'payinfo2'} =~ /^([\dx]+)$/
659 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
661 $payinfo = $payinfo1. '@'. $payinfo2;
663 $payinfo = $cust_main->payinfo
664 if $cust_main->paymask eq $payinfo;
666 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
668 $payinfo = $p->{'payinfo'};
670 #more intelligent mathing will be needed here if you change
671 #card_masking_method and don't remove existing paymasks
672 $payinfo = $cust_main->payinfo
673 if $cust_main->paymask eq $payinfo;
676 $payinfo =~ /^(\d{13,16})$/
677 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
681 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
682 return { 'error' => gettext('unknown_card_type') }
683 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
685 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
686 if ( cardtype($payinfo) eq 'American Express card' ) {
687 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
688 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
691 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
692 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
698 die "unknown payby $payby";
702 'CARD' => [ qw( paystart_month paystart_year payissue payip
703 address1 address2 city state zip country ) ],
704 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
707 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
709 'payinfo' => $payinfo,
710 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
711 'payname' => $payname,
712 'paybatch' => $paybatch, #this doesn't actually do anything
714 'paynum_ref' => \$paynum,
715 'pkgnum' => $session->{'pkgnum'},
716 'discount_term' => $discount_term,
718 map { $_ => $p->{$_} } @{ $payby2fields{$payby} }
720 return { 'error' => $error } if $error;
722 $cust_main->apply_payments;
724 if ( $p->{'save'} ) {
725 my $new = new FS::cust_main { $cust_main->hash };
726 if ($payby eq 'CARD' || $payby eq 'DCRD') {
727 $new->set( $_ => $p->{$_} )
728 foreach qw( payname paystart_month paystart_year payissue payip
729 address1 address2 city state zip country );
730 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
731 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
732 $new->set( $_ => $p->{$_} )
733 foreach qw( payname payip paytype paystate
734 stateid stateid_state );
735 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
737 $new->set( 'payinfo' => $cust_main->card_token || $payinfo );
738 $new->set( 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01' );
739 my $error = $new->replace($cust_main);
741 #no, this causes customers to process their payments again
742 #return { 'error' => $error };
743 #XXX just warn verosely for now so i can figure out how these happen in
744 # the first place, eventually should redirect them to the "change
745 #address" page but indicate the payment did process??
746 delete($p->{'payinfo'}); #don't want to log this!
747 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
748 "NEW: ". Dumper($new)."\n".
749 "OLD: ". Dumper($cust_main)."\n".
750 "PACKET: ". Dumper($p)."\n";
757 my $receipt_html = '';
759 # currently supported for realtime CC only; send receipt data to SS
760 my $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
763 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
766 <TD ALIGN="right">Payment#</TD>
767 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
771 <TD ALIGN="right">Date</TD>
773 <TD BGCOLOR="#FFFFFF"><B>! .
774 time2str("%a %b %o, %Y %r", $cust_pay->_date)
780 <TD ALIGN="right">Amount</TD>
781 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paid . qq!</B></TD>
786 <TD ALIGN="right">Payment method</TD>
787 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
796 return { 'error' => '', 'receipt_html' => $receipt_html, };
800 sub realtime_collect {
803 my $session = _cache->get($p->{'session_id'})
804 or return { 'error' => "Can't resume session" }; #better error message
806 my $custnum = $session->{'custnum'};
808 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
809 or return { 'error' => "unknown custnum $custnum" };
812 if ( $p->{'amount'} ) {
813 $amount = $p->{'amount'};
815 elsif ( $session->{'pkgnum'} ) {
816 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
819 $amount = $cust_main->balance;
822 my $error = $cust_main->realtime_collect(
823 'method' => $p->{'method'},
825 'pkgnum' => $session->{'pkgnum'},
826 'session_id' => $p->{'session_id'},
830 return { 'error' => $error } unless ref( $error );
832 return { 'error' => '', amount => $amount, %$error };
835 sub process_payment_order_pkg {
838 my $hr = process_payment($p);
839 return $hr if $hr->{'error'};
844 sub process_payment_order_renew {
847 my $hr = process_payment($p);
848 return $hr if $hr->{'error'};
857 my $session = _cache->get($p->{'session_id'})
858 or return { 'error' => "Can't resume session" }; #better error message
862 my $custnum = $session->{'custnum'};
864 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
865 or return { 'error' => "unknown custnum $custnum" };
867 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
868 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
876 return { 'error' => $error } if $error;
878 return { 'error' => '',
880 'seconds' => $seconds,
881 'duration' => duration_exact($seconds),
882 'upbytes' => $upbytes,
883 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
884 'downbytes' => $downbytes,
885 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
886 'totalbytes'=> $totalbytes,
887 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
894 my $session = _cache->get($p->{'session_id'})
895 or return { 'error' => "Can't resume session" }; #better error message
897 my $custnum = $session->{'custnum'};
899 my $invnum = $p->{'invnum'};
901 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
902 'custnum' => $custnum } )
903 or return { 'error' => "Can't find invnum" };
907 return { 'error' => '',
909 'invoice_text' => join('', $cust_bill->print_text ),
910 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
918 #sessioning for this? how do we get the session id to the backend invoice
919 # template so it can add it to the link, blah
922 if ( $p->{'invnum'} ) {
923 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
924 or return { 'error' => 'unknown invnum' };
925 $agentnum = $cust_bill->cust_main->agentnum;
928 my $templatename = $p->{'template'} || $p->{'templatename'};
930 #false laziness-ish w/view/cust_bill-logo.cgi
932 my $conf = new FS::Conf;
933 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
934 $templatename = "_$1";
939 my $filename = "logo$templatename.png";
941 return { 'error' => '',
942 'logo' => $conf->config_binary($filename, $agentnum),
943 'content_type' => 'image/png', #should allow gif, jpg too
950 my $session = _cache->get($p->{'session_id'})
951 or return { 'error' => "Can't resume session" }; #better error message
953 my $custnum = $session->{'custnum'};
955 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
956 or return { 'error' => "unknown custnum $custnum" };
958 my @cust_bill = $cust_main->cust_bill;
960 return { 'error' => '',
961 'invoices' => [ map { { 'invnum' => $_->invnum,
962 '_date' => $_->_date,
963 'date' => time2str("%b %o, %Y", $_->_date),
972 my $session = _cache->get($p->{'session_id'})
973 or return { 'error' => "Can't resume session" }; #better error message
975 my $custnum = $session->{'custnum'};
977 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
978 or return { 'error' => "unknown custnum $custnum" };
980 my @errors = $cust_main->cancel( 'quiet'=>1 );
982 my $error = scalar(@errors) ? join(' / ', @errors) : '';
984 return { 'error' => $error };
991 my($context, $session, $custnum) = _custoragent_session_custnum($p);
992 return { 'error' => $session } if $context eq 'error';
994 my $search = { 'custnum' => $custnum };
995 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
996 my $cust_main = qsearchs('cust_main', $search )
997 or return { 'error' => "unknown custnum $custnum" };
999 my $conf = new FS::Conf;
1001 # the duplication below is necessary:
1002 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1003 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1004 # non-backwards-compatible change breaking the software of anyone using the API
1005 # instead of the stock selfservice
1006 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1007 if( $conf->exists('selfservice_server-view-wholesale') ) {
1008 return { 'svcnum' => $session->{'svcnum'},
1009 'custnum' => $custnum,
1010 'cust_pkg' => [ map {
1012 part_pkg => [ map $_->hashref, $_->part_pkg ],
1014 [ map $_->hashref, $_->available_part_svc ],
1016 [ map { my $ref = { $_->hash,
1017 label => [ $_->label ],
1019 $ref->{_password} = $_->svc_x->_password
1020 if $context eq 'agent'
1021 && $conf->exists('agent-showpasswords')
1022 && $_->part_svc->svcdb eq 'svc_acct';
1027 } $cust_main->cust_pkg
1030 small_custview( $cust_main, $conf->config('countrydefault') ),
1031 'wholesale_view' => 1,
1032 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1033 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1034 'lnp' => $conf->exists('svc_phone-lnp'),
1038 { 'svcnum' => $session->{'svcnum'},
1039 'custnum' => $custnum,
1040 'cust_pkg' => [ map {
1044 [ map $_->hashref, $_->available_part_svc ],
1046 [ map { my $ref = { $_->hash,
1047 label => [ $_->label ],
1049 $ref->{_password} = $_->svc_x->_password
1050 if $context eq 'agent'
1051 && $conf->exists('agent-showpasswords')
1052 && $_->part_svc->svcdb eq 'svc_acct';
1053 $ref->{svchash} = { $_->svc_x->hash } if
1054 $_->part_svc->svcdb eq 'svc_phone';
1055 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1056 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1061 } $cust_main->ncancelled_pkgs
1064 small_custview( $cust_main, $conf->config('countrydefault') ),
1072 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1073 return { 'error' => $session } if $context eq 'error';
1075 my $search = { 'custnum' => $custnum };
1076 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1077 my $cust_main = qsearchs('cust_main', $search )
1078 or return { 'error' => "unknown custnum $custnum" };
1081 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1082 foreach my $cust_pkg ( $p->{'ncancelled'}
1083 ? $cust_main->ncancelled_pkgs
1084 : $cust_main->unsuspended_pkgs ) {
1085 next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1086 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1088 if ( $p->{'svcdb'} ) {
1089 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1091 : ref($p->{'svcdb'}) eq 'ARRAY'
1092 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1093 : { $p->{'svcdb'} => 1 };
1094 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1097 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1100 my $conf = new FS::Conf;
1103 'svcnum' => $session->{'svcnum'},
1104 'custnum' => $custnum,
1105 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1106 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1109 my $svc_x = $_->svc_x;
1110 my($label, $value) = $_->label;
1111 my $svcdb = $_->part_svc->svcdb;
1112 my $part_pkg = $_->cust_pkg->part_pkg;
1115 'svcnum' => $_->svcnum,
1121 if ( $svcdb eq 'svc_acct' ) {
1124 'username' => $svc_x->username,
1125 'email' => $svc_x->email,
1126 'seconds' => $svc_x->seconds,
1127 'upbytes' => display_bytecount($svc_x->upbytes),
1128 'downbytes' => display_bytecount($svc_x->downbytes),
1129 'totalbytes' => display_bytecount($svc_x->totalbytes),
1131 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1132 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1133 'recharge_upbytes' =>
1134 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1135 'recharge_downbytes' =>
1136 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1137 'recharge_totalbytes' =>
1138 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1142 } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1158 _usage_details( \&_port_graph, $p,
1159 'svcdb' => 'svc_port',
1164 my($svc_port, $begin, $end) = @_;
1166 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1167 push @usage, { 'png' => $pngOrError };
1171 sub _list_svc_usage {
1172 my($svc_acct, $begin, $end) = @_;
1174 foreach my $part_export (
1175 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1176 qw( sqlradius sqlradius_withdomain )
1178 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1183 sub list_svc_usage {
1184 _usage_details(\&_list_svc_usage, @_);
1187 sub _list_support_usage {
1188 my($svc_acct, $begin, $end) = @_;
1190 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1191 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1193 push @usage, { 'seconds' => $_->seconds,
1194 'support' => $_->support,
1195 '_date' => $_->_date,
1196 'id' => $_->transaction_id,
1197 'creator' => $_->creator,
1198 'subject' => $_->subject,
1199 'status' => $_->status,
1200 'ticketid' => $_->ticketid,
1206 sub list_support_usage {
1207 _usage_details(\&_list_support_usage, @_);
1210 sub _list_cdr_usage {
1211 my($svc_phone, $begin, $end) = @_;
1212 map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1213 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1216 sub list_cdr_usage {
1218 _usage_details( \&_list_cdr_usage, $p,
1219 'svcdb' => 'svc_phone',
1223 sub _usage_details {
1224 my($callback, $p, %opt) = @_;
1226 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1227 return { 'error' => $session } if $context eq 'error';
1229 my $search = { 'svcnum' => $p->{'svcnum'} };
1230 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1232 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1234 my $svc_x = qsearchs( $svcdb, $search );
1235 return { 'error' => 'No service selected in list_svc_usage' }
1238 my $header = $svcdb eq 'svc_phone'
1239 ? [ split(',', FS::cdr::invoice_header('default') ) ] #XXX
1242 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1243 my $freq = $cust_pkg->part_pkg->freq;
1244 my $start = $cust_pkg->setup;
1245 #my $end = $cust_pkg->bill; # or time?
1248 unless ( $p->{beginning} ) {
1249 $p->{beginning} = $cust_pkg->last_bill;
1250 $p->{ending} = $end;
1253 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1255 #kinda false laziness with FS::cust_main::bill, but perhaps
1256 #we should really change this bit to DateTime and DateTime::Duration
1258 #change this bit to use Date::Manip? CAREFUL with timezones (see
1259 # mailing list archive)
1260 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1261 (localtime($p->{ending}) )[0,1,2,3,4,5];
1262 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1263 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1265 if ( $freq =~ /^\d+$/ ) {
1267 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1269 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1270 } elsif ( $freq =~ /^(\d+)w$/ ) {
1272 $nmday += $weeks * 7;
1273 $pmday -= $weeks * 7;
1274 } elsif ( $freq =~ /^(\d+)d$/ ) {
1278 } elsif ( $freq =~ /^(\d+)h$/ ) {
1283 return { 'error' => "unparsable frequency: ". $freq };
1286 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1287 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1291 'svcnum' => $p->{svcnum},
1292 'beginning' => $p->{beginning},
1293 'ending' => $p->{ending},
1294 'previous' => ($previous > $start) ? $previous : $start,
1295 'next' => ($next < $end) ? $next : $end,
1296 'header' => $header,
1304 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1305 return { 'error' => $session } if $context eq 'error';
1307 my $search = { 'custnum' => $custnum };
1308 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1309 my $cust_main = qsearchs('cust_main', $search )
1310 or return { 'error' => "unknown custnum $custnum" };
1312 my $status = $cust_main->status;
1313 #false laziness w/ClientAPI/Signup.pm
1315 my $cust_pkg = new FS::cust_pkg ( {
1316 'custnum' => $custnum,
1317 'pkgpart' => $p->{'pkgpart'},
1319 my $error = $cust_pkg->check;
1320 return { 'error' => $error } if $error;
1323 unless ( $p->{'svcpart'} eq 'none' ) {
1327 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1329 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1330 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1331 $svcdb = $part_svc->svcdb;
1333 $svcdb = 'svc_acct';
1335 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1338 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
1339 'svc_domain' => [ qw( domain ) ],
1340 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
1341 'svc_external' => [ qw( id title ) ],
1342 'svc_pbx' => [ qw( id title ) ],
1345 my $svc_x = "FS::$svcdb"->new( {
1346 'svcpart' => $svcpart,
1347 map { $_ => $p->{$_} } @{$fields{$svcdb}}
1350 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1353 while ( length($p->{"snarf_machine$snarfnum"}) ) {
1354 my $acct_snarf = new FS::acct_snarf ( {
1355 'machine' => $p->{"snarf_machine$snarfnum"},
1356 'protocol' => $p->{"snarf_protocol$snarfnum"},
1357 'username' => $p->{"snarf_username$snarfnum"},
1358 '_password' => $p->{"snarf_password$snarfnum"},
1361 push @acct_snarf, $acct_snarf;
1363 $svc_x->child_objects( \@acct_snarf );
1366 my $y = $svc_x->setdefault; # arguably should be in new method
1367 return { 'error' => $y } if $y && !ref($y);
1369 $error = $svc_x->check;
1370 return { 'error' => $error } if $error;
1377 tie my %hash, 'Tie::RefHash';
1378 %hash = ( $cust_pkg => \@svc );
1380 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1381 return { 'error' => $error } if $error;
1383 my $conf = new FS::Conf;
1384 if ( $conf->exists('signup_server-realtime') ) {
1386 my $bill_error = _do_bop_realtime( $cust_main, $status );
1389 $cust_pkg->cancel('quiet'=>1);
1392 $cust_pkg->reexport;
1396 $cust_pkg->reexport;
1399 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1401 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1408 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1409 return { 'error' => $session } if $context eq 'error';
1411 my $search = { 'custnum' => $custnum };
1412 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1413 my $cust_main = qsearchs('cust_main', $search )
1414 or return { 'error' => "unknown custnum $custnum" };
1416 my $status = $cust_main->status;
1417 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1418 or return { 'error' => "unknown package $p->{pkgnum}" };
1421 my $error = FS::cust_pkg::order( $custnum,
1427 my $conf = new FS::Conf;
1428 if ( $conf->exists('signup_server-realtime') ) {
1430 my $bill_error = _do_bop_realtime( $cust_main, $status );
1433 $newpkg[0]->suspend;
1436 $newpkg[0]->reexport;
1440 $newpkg[0]->reexport;
1443 return { error => '', pkgnum => $cust_pkg->pkgnum };
1447 sub order_recharge {
1450 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1451 return { 'error' => $session } if $context eq 'error';
1453 my $search = { 'custnum' => $custnum };
1454 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1455 my $cust_main = qsearchs('cust_main', $search )
1456 or return { 'error' => "unknown custnum $custnum" };
1458 my $status = $cust_main->status;
1459 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1460 or return { 'error' => "unknown service " . $p->{'svcnum'} };
1462 my $svc_x = $cust_svc->svc_x;
1463 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1466 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
1467 qw ( recharge_seconds recharge_upbytes recharge_downbytes
1468 recharge_totalbytes );
1469 my $amount = $part_pkg->option('recharge_amount', 1);
1471 my ($l, $v, $d) = $cust_svc->label; # blah
1472 my $pkg = "Recharge $v";
1474 my $bill_error = $cust_main->charge($amount, $pkg,
1475 "time: $vhash{seconds}, up: $vhash{upbytes}," .
1476 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1477 $part_pkg->taxclass); #meh
1479 my $conf = new FS::Conf;
1480 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1482 $bill_error = _do_bop_realtime( $cust_main, $status );
1487 my $error = $svc_x->recharge (\%vhash);
1488 return { 'error' => $error } if $error;
1492 my $error = $bill_error;
1493 $error ||= $svc_x->recharge (\%vhash);
1494 return { 'error' => $error } if $error;
1497 return { error => '', svc => $cust_svc->part_svc->svc };
1501 sub _do_bop_realtime {
1502 my ($cust_main, $status) = (shift, shift);
1504 my $old_balance = $cust_main->balance;
1506 my $bill_error = $cust_main->bill
1507 || $cust_main->apply_payments_and_credits
1508 || $cust_main->realtime_collect('selfservice' => 1);
1510 if ( $cust_main->balance > $old_balance
1511 && $cust_main->balance > 0
1512 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1513 1 : $status eq 'suspended' ) ) {
1514 #this makes sense. credit is "un-doing" the invoice
1515 my $conf = new FS::Conf;
1516 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1517 'self-service decline',
1518 'reason_type' => $conf->config('signup_credit_type'),
1520 $cust_main->apply_credits( 'order' => 'newest' );
1522 return { 'error' => '_decline', 'bill_error' => $bill_error };
1531 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1532 return { 'error' => $session } if $context eq 'error';
1534 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1535 or return { 'error' => "unknown custnum $custnum" };
1537 my @cust_pkg = sort { $a->bill <=> $b->bill }
1538 grep { $_->part_pkg->freq ne '0' }
1539 $cust_main->ncancelled_pkgs;
1541 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1543 my $total = $cust_main->balance;
1546 my $bill = $_->bill;
1547 $total += $_->part_pkg->base_recur($_, \$bill);
1548 my $renew_date = $_->part_pkg->add_freq($_->bill);
1550 'pkgnum' => $_->pkgnum,
1551 'amount' => sprintf('%.2f', $total),
1552 'bill_date' => $_->bill,
1553 'bill_date_pretty' => time2str('%x', $_->bill),
1554 'renew_date' => $renew_date,
1555 'renew_date_pretty' => time2str('%x', $renew_date),
1556 'expire_date' => $_->expire,
1557 'expire_date_pretty' => time2str('%x', $_->expire),
1562 return { 'dates' => \@array };
1566 sub payment_info_renew_info {
1568 my $renew_info = renew_info($p);
1569 my $payment_info = payment_info($p);
1570 return { %$renew_info,
1578 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1579 return { 'error' => $session } if $context eq 'error';
1581 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1582 or return { 'error' => "unknown custnum $custnum" };
1584 my $date = $p->{'date'};
1588 #freeside-daily -n -d $date fs_daily $custnum
1589 $cust_main->bill_and_collect( 'time' => $date,
1590 'invoice_time' => $now,
1591 'actual_time' => $now,
1592 'check_freq' => '1d',
1595 return { 'error' => '' };
1601 my $session = _cache->get($p->{'session_id'})
1602 or return { 'error' => "Can't resume session" }; #better error message
1604 my $custnum = $session->{'custnum'};
1606 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1607 or return { 'error' => "unknown custnum $custnum" };
1609 my $conf = new FS::Conf;
1611 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1612 or return { 'error' => 'Permission denied' };
1614 my $pkgnum = $p->{'pkgnum'};
1616 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1617 'pkgnum' => $pkgnum, } )
1618 or return { 'error' => "unknown pkgnum $pkgnum" };
1620 my $error = $cust_pkg->suspend(reason => $reasonnum);
1621 return { 'error' => $error };
1627 my $session = _cache->get($p->{'session_id'})
1628 or return { 'error' => "Can't resume session" }; #better error message
1630 my $custnum = $session->{'custnum'};
1632 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1633 or return { 'error' => "unknown custnum $custnum" };
1635 my $pkgnum = $p->{'pkgnum'};
1637 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1638 'pkgnum' => $pkgnum, } )
1639 or return { 'error' => "unknown pkgnum $pkgnum" };
1641 my $error = $cust_pkg->cancel('quiet' => 1);
1642 return { 'error' => $error };
1646 sub provision_phone {
1649 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1651 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1652 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1653 return { 'error' => $session } if $context eq 'error';
1655 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1656 return { 'error' => 'service not found' } unless $svc_phone;
1657 return { 'error' => 'invalid svcnum' }
1658 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1660 $svc_phone->email($p->{'email'})
1661 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1662 $svc_phone->forwarddst($p->{'forwarddst'})
1663 if $svc_phone->forwarddst ne $p->{'forwarddst'}
1664 && $p->{'forwarddst'} =~ /^(\d+|)$/;
1665 return { 'error' => $svc_phone->replace };
1669 unless($p->{'lnp'}) {
1670 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1671 $p->{'lnp_status'} = "portingin";
1672 return _provision( 'FS::svc_phone',
1673 [qw(lnp_desired_due_date lnp_other_provider
1674 lnp_other_provider_account phonenum countrycode lnp_status)],
1675 [qw(phonenum countrycode)],
1682 unless (scalar(@bulkdid)) {
1683 return _provision( 'FS::svc_phone',
1684 [qw(phonenum countrycode)],
1685 [qw(phonenum countrycode)],
1691 # bulk DID order case
1693 foreach my $did ( @bulkdid ) {
1694 $did =~ s/[^0-9]//g;
1695 $error = _provision( 'FS::svc_phone',
1696 [qw(phonenum countrycode)],
1697 [qw(phonenum countrycode)],
1699 'pkgnum' => $p->{'pkgnum'},
1700 'svcpart' => $p->{'svcpart'},
1702 'countrycode' => $p->{'countrycode'},
1703 'session_id' => $p->{'session_id'},
1706 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1708 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1711 sub provision_acct {
1713 warn "provision_acct called\n"
1716 return { 'error' => gettext('passwords_dont_match') }
1717 if $p->{'_password'} ne $p->{'_password2'};
1718 return { 'error' => gettext('empty_password') }
1719 unless length($p->{'_password'});
1721 if ($p->{'domsvc'}) {
1722 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1723 qw ( svcpart pkgnum ) );
1724 return { 'error' => gettext('invalid_domain') }
1725 unless ($domains{$p->{'domsvc'}});
1728 warn "provision_acct calling _provision\n"
1730 _provision( 'FS::svc_acct',
1731 [qw(username _password domsvc)],
1732 [qw(username _password domsvc)],
1738 sub provision_external {
1740 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1741 _provision( 'FS::svc_external',
1750 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1751 warn "_provision called for $class\n"
1754 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1755 return { 'error' => $session } if $context eq 'error';
1757 my $search = { 'custnum' => $custnum };
1758 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1759 my $cust_main = qsearchs('cust_main', $search )
1760 or return { 'error' => "unknown custnum $custnum" };
1762 my $pkgnum = $p->{'pkgnum'};
1764 warn "searching for custnum $custnum pkgnum $pkgnum\n"
1766 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1767 'pkgnum' => $pkgnum,
1769 or return { 'error' => "unknown pkgnum $pkgnum" };
1771 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1773 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1774 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1776 warn "creating $class record\n"
1778 my $svc_x = $class->new( {
1779 'pkgnum' => $p->{'pkgnum'},
1780 'svcpart' => $p->{'svcpart'},
1781 map { $_ => $p->{$_} } @$fields
1783 warn "inserting $class record\n"
1785 my $error = $svc_x->insert;
1788 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1790 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1793 my $return = { 'svc' => $part_svc->svc,
1795 map { $_ => $svc_x->get($_) } @$return_fields
1797 warn "_provision returning ". Dumper($return). "\n"
1806 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1807 return { 'error' => $session } if $context eq 'error';
1809 my $search = { 'custnum' => $custnum };
1810 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1811 my $cust_main = qsearchs('cust_main', $search )
1812 or return { 'error' => "unknown custnum $custnum" };
1814 my $pkgnum = $p->{'pkgnum'};
1816 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1817 'pkgnum' => $pkgnum,
1819 or return { 'error' => "unknown pkgnum $pkgnum" };
1821 my $svcpart = $p->{'svcpart'};
1823 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1824 'svcpart' => $svcpart, } )
1825 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1826 my $part_svc = $pkg_svc->part_svc;
1828 my $conf = new FS::Conf;
1831 'svc' => $part_svc->svc,
1832 'svcdb' => $part_svc->svcdb,
1833 'pkgnum' => $pkgnum,
1834 'svcpart' => $svcpart,
1835 'custnum' => $custnum,
1837 'security_phrase' => 0, #XXX !
1838 'svc_acct_pop' => [], #XXX !
1840 'init_popstate' => '',
1845 small_custview( $cust_main, $conf->config('countrydefault') ),
1849 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
1850 && $ret->{'svcdb'} eq 'svc_phone') {
1851 $ret->{'svcnum'} = $p->{'svcnum'};
1852 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1853 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
1854 $ret->{'email'} = $svc_phone->email;
1855 $ret->{'forwarddst'} = $svc_phone->forwarddst;
1862 sub unprovision_svc {
1865 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1866 return { 'error' => $session } if $context eq 'error';
1868 my $search = { 'custnum' => $custnum };
1869 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1870 my $cust_main = qsearchs('cust_main', $search )
1871 or return { 'error' => "unknown custnum $custnum" };
1873 my $svcnum = $p->{'svcnum'};
1875 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
1876 or return { 'error' => "unknown svcnum $svcnum" };
1878 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1879 unless $cust_svc->cust_pkg->custnum == $custnum;
1881 my $conf = new FS::Conf;
1883 return { 'svc' => $cust_svc->part_svc->svc,
1884 'error' => $cust_svc->cancel,
1886 small_custview( $cust_main, $conf->config('countrydefault') ),
1891 sub myaccount_passwd {
1893 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1894 return { 'error' => $session } if $context eq 'error';
1896 return { 'error' => "New passwords don't match." }
1897 if $p->{'new_password'} ne $p->{'new_password2'};
1899 return { 'error' => 'Enter new password' }
1900 unless length($p->{'new_password'});
1902 #my $search = { 'custnum' => $custnum };
1903 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1904 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1905 my $search = " AND custnum = $1";
1906 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1908 my $svc_acct = qsearchs( {
1909 'table' => 'svc_acct',
1910 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1911 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
1912 'LEFT JOIN cust_main USING ( custnum ) ',
1913 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
1914 'extra_sql' => $search, #important
1916 or return { 'error' => "Service not found" };
1918 $svc_acct->_password($p->{'new_password'});
1919 my $error = $svc_acct->replace();
1921 my($label, $value) = $svc_acct->cust_svc->label;
1923 return { 'error' => $error,
1932 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1933 return { 'error' => $session } if $context eq 'error';
1935 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
1936 FS::TicketSystem->init();
1938 my $conf = new FS::Conf;
1939 my $queue = $p->{'queue'}
1940 || $conf->config('ticket_system-selfservice_queueid')
1941 || $conf->config('ticket_system-default_queueid');
1943 warn "$me create_ticket: creating ticket\n" if $DEBUG;
1944 my $err_or_ticket = FS::TicketSystem->create_ticket(
1945 '', #create RT session based on FS CurrentUser (fs_selfservice)
1947 'custnum' => $custnum,
1948 'svcnum' => $session->{'svcnum'},
1949 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
1952 if ( ref($err_or_ticket) ) {
1953 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
1955 return { 'error' => '',
1956 'ticket_id' => $err_or_ticket->id,
1959 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
1961 return { 'error' => $err_or_ticket };
1969 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1970 return { 'error' => $session } if $context eq 'error';
1972 return { error => 'requested format not implemented' }
1973 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
1975 my $conf = new FS::Conf;
1976 my $age_threshold = 0;
1977 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
1978 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
1980 my $search = { 'custnum' => $custnum };
1981 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1982 my $cust_main = qsearchs('cust_main', $search )
1983 or return { 'error' => "unknown custnum $custnum" };
1985 # does it make more sense to just run one sql query for this instead of all the
1986 # insanity below? would increase performance greately for large data sets?
1988 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1989 my @part_svc = $cust_pkg->part_svc;
1990 foreach my $part_svc ( @part_svc ) {
1991 if($part_svc->svcdb eq 'svc_phone'){
1992 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
1993 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
1994 push @svc_phone, $cust_pkg_svc->svc_x
1995 if $cust_pkg_svc->date_inserted >= $age_threshold;
2003 my($xls_r,$xls_c) = (0,0);
2006 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2007 if($p->{'format'} eq 'csv') {
2008 $csv = new Text::CSV_XS { 'always_quote' => 1,
2011 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2012 $content .= $csv->string;
2014 elsif($p->{'format'} eq 'xls') {
2015 my $XLS1 = new IO::Scalar \$content;
2016 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2017 or return { 'error' => "Error opening .xls file: $!" };
2018 $xls = $xls_workbook->add_worksheet('DIDs');
2019 foreach ( @fields ) {
2020 $xls->write(0,$xls_c++,$_);
2025 foreach my $svc_phone ( @svc_phone ) {
2026 my @cols = map { $svc_phone->$_ } @fields;
2027 if($p->{'format'} eq 'csv') {
2028 return { 'error' => 'Unable to create CSV' }
2029 unless $csv->combine(@cols);
2030 $content .= $csv->string;
2032 elsif($p->{'format'} eq 'xls') {
2035 $xls->write($xls_r,$xls_c++,$_);
2041 $xls_workbook->close() if $p->{'format'} eq 'xls';
2043 { content => $content, format => $p->{'format'}, };
2048 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2049 return { 'error' => $session } if $context eq 'error';
2051 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2052 FS::TicketSystem->init();
2053 return { 'error' => 'get_ticket configuration error' }
2054 if $FS::TicketSystem::system ne 'RT_Internal';
2056 # check existence and ownership as part of this
2057 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2058 my $rt_session = FS::TicketSystem->session('');
2059 my $Ticket = FS::TicketSystem->get_ticket_object(
2061 ticket_id => $p->{'ticket_id'},
2064 return { 'error' => 'ticket not found' } if !$Ticket;
2066 if ( length( $p->{'subject'} || '' ) ) {
2068 if ( $p->{'subject'} ne $Ticket->Subject ) {
2069 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2070 return { 'error' => "unable to set subject: $msg" } if !$val;
2074 if(length($p->{'reply'})) {
2075 my @err_or_res = FS::TicketSystem->correspond_ticket(
2077 'ticket_id' => $p->{'ticket_id'},
2078 'content' => $p->{'reply'},
2081 return { 'error' => 'unable to reply to ticket' }
2082 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2085 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2086 my $err_or_ticket = FS::TicketSystem->get_ticket(
2088 'ticket_id' => $p->{'ticket_id'},
2091 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2092 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2094 return { 'error' => $err_or_ticket };
2097 my @custs = @{$err_or_ticket->{'custs'}};
2098 my @txns = @{$err_or_ticket->{'txns'}};
2101 # superseded by check in get_ticket_object
2102 #return { 'error' => 'invalid ticket requested' }
2103 #unless grep($_ eq $custnum, @custs);
2105 foreach my $txn ( @txns ) {
2106 push @filtered_txns, $txn
2107 if ($txn->{'type'} eq 'EmailRecord'
2108 || $txn->{'type'} eq 'Correspond'
2109 || $txn->{'type'} eq 'Create');
2112 warn "$me get_ticket: successful: \n"
2114 return { 'error' => '',
2115 'transactions' => \@filtered_txns,
2116 'ticket_fields' => $err_or_ticket->{'fields'},
2117 'ticket_id' => $p->{'ticket_id'},
2121 sub adjust_ticket_priority {
2123 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2124 return { 'error' => $session } if $context eq 'error';
2126 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2127 FS::TicketSystem->init;
2128 my $ss_priority = FS::TicketSystem->selfservice_priority;
2130 return { 'error' => 'adjust_ticket_priority configuration error' }
2131 if $FS::TicketSystem::system ne 'RT_Internal'
2134 my $values = $p->{'values'}; #hashref, id => priority value
2137 foreach my $id (keys %$values) {
2138 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2139 my $Ticket = FS::TicketSystem->get_ticket_object('',
2141 'custnum' => $custnum,
2144 $ticket_error{$id} = 'ticket not found';
2148 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2149 # We're not going to implement it for RT_External.
2150 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2151 my $new_value = $values->{$id};
2152 next if $old_value eq $new_value;
2154 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2156 # AddCustomFieldValue works fine (replacing any existing value) if it's
2157 # a single-valued custom field, which it should be. If it's not, you're
2158 # doing something wrong.
2160 if ( length($new_value) ) {
2161 ($val, $msg) = $Ticket->AddCustomFieldValue(
2162 Field => $ss_priority,
2163 Value => $new_value,
2167 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2168 Field => $ss_priority,
2169 Value => $old_value,
2173 $ticket_error{$id} = $msg if !$val;
2174 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2176 return { 'error' => '',
2177 'ticket_error' => \%ticket_error,
2178 %{ customer_info($p) } # send updated customer info back
2184 sub _custoragent_session_custnum {
2187 my($context, $session, $custnum);
2188 if ( $p->{'session_id'} ) {
2190 $context = 'customer';
2191 $session = _cache->get($p->{'session_id'})
2192 or return ( 'error' => "Can't resume session" ); #better error message
2193 $custnum = $session->{'custnum'};
2195 } elsif ( $p->{'agent_session_id'} ) {
2198 my $agent_cache = new FS::ClientAPI_SessionCache( {
2199 'namespace' => 'FS::ClientAPI::Agent',
2201 $session = $agent_cache->get($p->{'agent_session_id'})
2202 or return ( 'error' => "Can't resume session" ); #better error message
2203 $custnum = $p->{'custnum'};
2207 return ( 'error' => "Can't resume session" ); #better error message
2210 ($context, $session, $custnum);