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 my @tickets = $cust_main->tickets;
343 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
344 if ( FS::TicketSystem->selfservice_priority ) {
345 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
349 ($a->{'_selfservice_priority'} eq '') <=>
350 ($b->{'_selfservice_priority'} eq '')
353 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
359 $return{tickets} = \@tickets;
362 unless ( $session->{'pkgnum'} ) {
365 invnum => $_->invnum,
366 date => time2str("%b %o, %Y", $_->_date),
369 } $cust_main->open_cust_bill;
370 $return{open_invoices} = \@open;
373 $return{small_custview} =
374 small_custview( $cust_main,
375 scalar($conf->config('countrydefault')),
376 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
379 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
381 for (@cust_main_editable_fields) {
382 $return{$_} = $cust_main->get($_);
385 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
386 $return{payinfo} = $cust_main->paymask;
387 @return{'month', 'year'} = $cust_main->paydate_monthyear;
390 $return{'invoicing_list'} =
391 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
392 $return{'postal_invoicing'} =
393 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
395 if (scalar($conf->config('support_packages'))) {
396 my @support_services = ();
397 foreach ($cust_main->support_services) {
398 my $seconds = $_->svc_x->seconds;
399 my $time_remaining = (($seconds < 0) ? '-' : '' ).
400 int(abs($seconds)/3600)."h".
401 sprintf("%02d",(abs($seconds)%3600)/60)."m";
402 my $cust_pkg = $_->cust_pkg;
405 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
406 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
407 push @support_services, { svcnum => $_->svcnum,
408 time => $time_remaining,
413 $return{support_services} = \@support_services;
416 if ( $conf->config('prepayment_discounts-credit_type') ) {
418 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
421 } elsif ( $session->{'svcnum'} ) { #no customer record
423 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
424 or die "unknown svcnum";
425 $return{name} = $svc_acct->email;
429 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
433 return { 'error' => '',
434 'custnum' => $custnum,
442 my $session = _cache->get($p->{'session_id'})
443 or return { 'error' => "Can't resume session" }; #better error message
445 my $custnum = $session->{'custnum'}
446 or return { 'error' => "no customer record" };
448 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
449 or return { 'error' => "unknown custnum $custnum" };
451 my $new = new FS::cust_main { $cust_main->hash };
452 $new->set( $_ => $p->{$_} )
453 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
456 if (exists($p->{'payby'})) {
457 $p->{'payby'} =~ /^([A-Z]{4})$/
458 or return { 'error' => "illegal_payby " . $p->{'payby'} };
462 if ( $payby =~ /^(CARD|DCRD)$/ ) {
464 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
466 if ( $new->payinfo eq $cust_main->paymask ) {
467 $new->payinfo($cust_main->payinfo);
469 $new->payinfo($p->{'payinfo'});
472 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
474 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
477 $p->{'payinfo1'} =~ /^([\dx]+)$/
478 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
480 $p->{'payinfo2'} =~ /^([\dx]+)$/
481 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
483 $payinfo = $payinfo1. '@'. $payinfo2;
485 $new->payinfo( ($payinfo eq $cust_main->paymask)
486 ? $cust_main->payinfo
490 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
492 } elsif ( $payby =~ /^(BILL)$/ ) {
494 } elsif ( $payby ) { #notyet ready
495 return { 'error' => "unknown payby $payby" };
499 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
500 #false laziness with httemplate/edit/process/cust_main.cgi
501 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
502 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
504 @invoicing_list = $cust_main->invoicing_list;
507 my $error = $new->replace($cust_main, \@invoicing_list);
508 return { 'error' => $error } if $error;
511 return { 'error' => '' };
516 my $session = _cache->get($p->{'session_id'})
517 or return { 'error' => "Can't resume session" }; #better error message
523 my $conf = new FS::Conf;
524 use vars qw($payment_info); #cache for performance
525 unless ( $payment_info ) {
527 my %states = map { $_->state => 1 }
528 qsearch('cust_main_county', {
529 'country' => $conf->config('countrydefault') || 'US'
532 my %cust_paybys = map { $_ => 1 }
533 map { FS::payby->payby2payment($_) }
534 $conf->config('signup_server-payby');
536 my @cust_paybys = keys %cust_paybys;
540 #list all counties/states/countries
541 'cust_main_county' =>
542 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
544 #shortcut for one-country folks
546 [ sort { $a cmp $b } keys %states ],
548 'card_types' => card_types(),
550 'paytypes' => [ @FS::cust_main::paytypes ],
552 'paybys' => [ $conf->config('signup_server-payby') ],
553 'cust_paybys' => \@cust_paybys,
555 'stateid_label' => FS::Msgcat::_gettext('stateid'),
556 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
558 'show_ss' => $conf->exists('show_ss'),
559 'show_stateid' => $conf->exists('show_stateid'),
560 'show_paystate' => $conf->exists('show_bankstate'),
562 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
564 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
573 my %return = %$payment_info;
575 my $custnum = $session->{'custnum'};
577 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
578 or return { 'error' => "unknown custnum $custnum" };
580 $return{'hide_payment_fields'} = [
582 my $pg = payment_gateway($cust_main, $_);
583 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
584 } @{ $return{cust_paybys} }
587 $return{balance} = $cust_main->balance; #XXX pkg-balances?
589 $return{payname} = $cust_main->payname
590 || ( $cust_main->first. ' '. $cust_main->get('last') );
592 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
594 $return{payby} = $cust_main->payby;
595 $return{stateid_state} = $cust_main->stateid_state;
597 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
598 $return{card_type} = cardtype($cust_main->payinfo);
599 $return{payinfo} = $cust_main->paymask;
601 @return{'month', 'year'} = $cust_main->paydate_monthyear;
605 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
606 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
607 $return{payinfo1} = $payinfo1;
608 $return{payinfo2} = $payinfo2;
609 $return{paytype} = $cust_main->paytype;
610 $return{paystate} = $cust_main->paystate;
614 if ( $conf->config('prepayment_discounts-credit_type') ) {
616 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
619 #doubleclick protection
621 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
623 return { 'error' => '',
629 #some false laziness with httemplate/process/payment.cgi - look there for
630 #ACH and CVV support stuff
631 sub process_payment {
635 my $session = _cache->get($p->{'session_id'})
636 or return { 'error' => "Can't resume session" }; #better error message
640 my $custnum = $session->{'custnum'};
642 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
643 or return { 'error' => "unknown custnum $custnum" };
645 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
646 or return { 'error' => gettext('illegal_amount') };
648 return { error => 'Amount must be greater than 0' } unless $amount > 0;
650 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
651 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
652 my $discount_term = $1;
654 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
655 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
658 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
659 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
662 $p->{'payby'} ||= 'CARD';
663 $p->{'payby'} =~ /^([A-Z]{4})$/
664 or return { 'error' => "illegal_payby " . $p->{'payby'} };
667 #false laziness w/process/payment.cgi
671 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
673 $p->{'payinfo1'} =~ /^([\dx]+)$/
674 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
676 $p->{'payinfo2'} =~ /^([\dx]+)$/
677 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
679 $payinfo = $payinfo1. '@'. $payinfo2;
681 $payinfo = $cust_main->payinfo
682 if $cust_main->paymask eq $payinfo;
684 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
686 $payinfo = $p->{'payinfo'};
688 #more intelligent mathing will be needed here if you change
689 #card_masking_method and don't remove existing paymasks
690 $payinfo = $cust_main->payinfo
691 if $cust_main->paymask eq $payinfo;
694 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
695 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
699 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
700 return { 'error' => gettext('unknown_card_type') }
701 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
703 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
704 if ( cardtype($payinfo) eq 'American Express card' ) {
705 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
706 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
709 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
710 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
716 die "unknown payby $payby";
720 'CARD' => [ qw( paystart_month paystart_year payissue payip
721 address1 address2 city state zip country ) ],
722 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
725 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
727 'payinfo' => $payinfo,
728 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
729 'payname' => $payname,
730 'paybatch' => $paybatch, #this doesn't actually do anything
732 'paynum_ref' => \$paynum,
733 'pkgnum' => $session->{'pkgnum'},
734 'discount_term' => $discount_term,
736 map { $_ => $p->{$_} } @{ $payby2fields{$payby} }
738 return { 'error' => $error } if $error;
740 $cust_main->apply_payments;
742 if ( $p->{'save'} ) {
743 my $new = new FS::cust_main { $cust_main->hash };
744 if ($payby eq 'CARD' || $payby eq 'DCRD') {
745 $new->set( $_ => $p->{$_} )
746 foreach qw( payname paystart_month paystart_year payissue payip
747 address1 address2 city state zip country );
748 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
749 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
750 $new->set( $_ => $p->{$_} )
751 foreach qw( payname payip paytype paystate
752 stateid stateid_state );
753 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
755 $new->set( 'payinfo' => $cust_main->card_token || $payinfo );
756 $new->set( 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01' );
757 my $error = $new->replace($cust_main);
759 #no, this causes customers to process their payments again
760 #return { 'error' => $error };
761 #XXX just warn verosely for now so i can figure out how these happen in
762 # the first place, eventually should redirect them to the "change
763 #address" page but indicate the payment did process??
764 delete($p->{'payinfo'}); #don't want to log this!
765 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
766 "NEW: ". Dumper($new)."\n".
767 "OLD: ". Dumper($cust_main)."\n".
768 "PACKET: ". Dumper($p)."\n";
775 my $receipt_html = '';
777 # currently supported for realtime CC only; send receipt data to SS
778 my $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
781 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
784 <TD ALIGN="right">Payment#</TD>
785 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
789 <TD ALIGN="right">Date</TD>
791 <TD BGCOLOR="#FFFFFF"><B>! .
792 time2str("%a %b %o, %Y %r", $cust_pay->_date)
798 <TD ALIGN="right">Amount</TD>
799 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paid . qq!</B></TD>
804 <TD ALIGN="right">Payment method</TD>
805 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
814 return { 'error' => '', 'receipt_html' => $receipt_html, };
818 sub realtime_collect {
821 my $session = _cache->get($p->{'session_id'})
822 or return { 'error' => "Can't resume session" }; #better error message
824 my $custnum = $session->{'custnum'};
826 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
827 or return { 'error' => "unknown custnum $custnum" };
830 if ( $p->{'amount'} ) {
831 $amount = $p->{'amount'};
833 elsif ( $session->{'pkgnum'} ) {
834 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
837 $amount = $cust_main->balance;
840 my $error = $cust_main->realtime_collect(
841 'method' => $p->{'method'},
843 'pkgnum' => $session->{'pkgnum'},
844 'session_id' => $p->{'session_id'},
848 return { 'error' => $error } unless ref( $error );
850 return { 'error' => '', amount => $amount, %$error };
853 sub process_payment_order_pkg {
856 my $hr = process_payment($p);
857 return $hr if $hr->{'error'};
862 sub process_payment_order_renew {
865 my $hr = process_payment($p);
866 return $hr if $hr->{'error'};
875 my $session = _cache->get($p->{'session_id'})
876 or return { 'error' => "Can't resume session" }; #better error message
880 my $custnum = $session->{'custnum'};
882 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
883 or return { 'error' => "unknown custnum $custnum" };
885 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
886 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
894 return { 'error' => $error } if $error;
896 return { 'error' => '',
898 'seconds' => $seconds,
899 'duration' => duration_exact($seconds),
900 'upbytes' => $upbytes,
901 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
902 'downbytes' => $downbytes,
903 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
904 'totalbytes'=> $totalbytes,
905 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
912 my $session = _cache->get($p->{'session_id'})
913 or return { 'error' => "Can't resume session" }; #better error message
915 my $custnum = $session->{'custnum'};
917 my $invnum = $p->{'invnum'};
919 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
920 'custnum' => $custnum } )
921 or return { 'error' => "Can't find invnum" };
925 return { 'error' => '',
927 'invoice_text' => join('', $cust_bill->print_text ),
928 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
936 #sessioning for this? how do we get the session id to the backend invoice
937 # template so it can add it to the link, blah
940 if ( $p->{'invnum'} ) {
941 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
942 or return { 'error' => 'unknown invnum' };
943 $agentnum = $cust_bill->cust_main->agentnum;
946 my $templatename = $p->{'template'} || $p->{'templatename'};
948 #false laziness-ish w/view/cust_bill-logo.cgi
950 my $conf = new FS::Conf;
951 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
952 $templatename = "_$1";
957 my $filename = "logo$templatename.png";
959 return { 'error' => '',
960 'logo' => $conf->config_binary($filename, $agentnum),
961 'content_type' => 'image/png', #should allow gif, jpg too
968 my $session = _cache->get($p->{'session_id'})
969 or return { 'error' => "Can't resume session" }; #better error message
971 my $custnum = $session->{'custnum'};
973 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
974 or return { 'error' => "unknown custnum $custnum" };
976 my @cust_bill = $cust_main->cust_bill;
978 return { 'error' => '',
979 'invoices' => [ map { { 'invnum' => $_->invnum,
980 '_date' => $_->_date,
981 'date' => time2str("%b %o, %Y", $_->_date),
990 my $session = _cache->get($p->{'session_id'})
991 or return { 'error' => "Can't resume session" }; #better error message
993 my $custnum = $session->{'custnum'};
995 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
996 or return { 'error' => "unknown custnum $custnum" };
998 my @errors = $cust_main->cancel( 'quiet'=>1 );
1000 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1002 return { 'error' => $error };
1009 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1010 return { 'error' => $session } if $context eq 'error';
1012 my $search = { 'custnum' => $custnum };
1013 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1014 my $cust_main = qsearchs('cust_main', $search )
1015 or return { 'error' => "unknown custnum $custnum" };
1017 my $conf = new FS::Conf;
1019 # the duplication below is necessary:
1020 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1021 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1022 # non-backwards-compatible change breaking the software of anyone using the API
1023 # instead of the stock selfservice
1024 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1025 if( $conf->exists('selfservice_server-view-wholesale') ) {
1026 return { 'svcnum' => $session->{'svcnum'},
1027 'custnum' => $custnum,
1028 'cust_pkg' => [ map {
1030 part_pkg => [ map $_->hashref, $_->part_pkg ],
1032 [ map $_->hashref, $_->available_part_svc ],
1034 [ map { my $ref = { $_->hash,
1035 label => [ $_->label ],
1037 $ref->{_password} = $_->svc_x->_password
1038 if $context eq 'agent'
1039 && $conf->exists('agent-showpasswords')
1040 && $_->part_svc->svcdb eq 'svc_acct';
1045 } $cust_main->cust_pkg
1048 small_custview( $cust_main, $conf->config('countrydefault') ),
1049 'wholesale_view' => 1,
1050 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1051 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1052 'lnp' => $conf->exists('svc_phone-lnp'),
1056 { 'svcnum' => $session->{'svcnum'},
1057 'custnum' => $custnum,
1058 'cust_pkg' => [ map {
1062 [ map $_->hashref, $_->available_part_svc ],
1064 [ map { my $ref = { $_->hash,
1065 label => [ $_->label ],
1067 $ref->{_password} = $_->svc_x->_password
1068 if $context eq 'agent'
1069 && $conf->exists('agent-showpasswords')
1070 && $_->part_svc->svcdb eq 'svc_acct';
1071 $ref->{svchash} = { $_->svc_x->hash } if
1072 $_->part_svc->svcdb eq 'svc_phone';
1073 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1074 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1079 } $cust_main->ncancelled_pkgs
1082 small_custview( $cust_main, $conf->config('countrydefault') ),
1090 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1091 return { 'error' => $session } if $context eq 'error';
1093 my $search = { 'custnum' => $custnum };
1094 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1095 my $cust_main = qsearchs('cust_main', $search )
1096 or return { 'error' => "unknown custnum $custnum" };
1099 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1100 foreach my $cust_pkg ( $p->{'ncancelled'}
1101 ? $cust_main->ncancelled_pkgs
1102 : $cust_main->unsuspended_pkgs ) {
1103 next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1104 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1106 if ( $p->{'svcdb'} ) {
1107 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1109 : ref($p->{'svcdb'}) eq 'ARRAY'
1110 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1111 : { $p->{'svcdb'} => 1 };
1112 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1115 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1118 my $conf = new FS::Conf;
1121 'svcnum' => $session->{'svcnum'},
1122 'custnum' => $custnum,
1123 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1124 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1127 my $svc_x = $_->svc_x;
1128 my($label, $value) = $_->label;
1129 my $svcdb = $_->part_svc->svcdb;
1130 my $part_pkg = $_->cust_pkg->part_pkg;
1133 'svcnum' => $_->svcnum,
1139 if ( $svcdb eq 'svc_acct' ) {
1142 'username' => $svc_x->username,
1143 'email' => $svc_x->email,
1144 'seconds' => $svc_x->seconds,
1145 'upbytes' => display_bytecount($svc_x->upbytes),
1146 'downbytes' => display_bytecount($svc_x->downbytes),
1147 'totalbytes' => display_bytecount($svc_x->totalbytes),
1149 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1150 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1151 'recharge_upbytes' =>
1152 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1153 'recharge_downbytes' =>
1154 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1155 'recharge_totalbytes' =>
1156 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1160 } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1176 _usage_details( \&_port_graph, $p,
1177 'svcdb' => 'svc_port',
1182 my($svc_port, $begin, $end) = @_;
1184 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1185 push @usage, { 'png' => $pngOrError };
1189 sub _list_svc_usage {
1190 my($svc_acct, $begin, $end) = @_;
1192 foreach my $part_export (
1193 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1194 qw( sqlradius sqlradius_withdomain )
1196 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1201 sub list_svc_usage {
1202 _usage_details(\&_list_svc_usage, @_);
1205 sub _list_support_usage {
1206 my($svc_acct, $begin, $end) = @_;
1208 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1209 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1211 push @usage, { 'seconds' => $_->seconds,
1212 'support' => $_->support,
1213 '_date' => $_->_date,
1214 'id' => $_->transaction_id,
1215 'creator' => $_->creator,
1216 'subject' => $_->subject,
1217 'status' => $_->status,
1218 'ticketid' => $_->ticketid,
1224 sub list_support_usage {
1225 _usage_details(\&_list_support_usage, @_);
1228 sub _list_cdr_usage {
1229 my($svc_phone, $begin, $end) = @_;
1230 map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1231 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1234 sub list_cdr_usage {
1236 _usage_details( \&_list_cdr_usage, $p,
1237 'svcdb' => 'svc_phone',
1241 sub _usage_details {
1242 my($callback, $p, %opt) = @_;
1244 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1245 return { 'error' => $session } if $context eq 'error';
1247 my $search = { 'svcnum' => $p->{'svcnum'} };
1248 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1250 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1252 my $svc_x = qsearchs( $svcdb, $search );
1253 return { 'error' => 'No service selected in list_svc_usage' }
1256 my $header = $svcdb eq 'svc_phone'
1257 ? [ split(',', FS::cdr::invoice_header('default') ) ] #XXX
1260 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1261 my $freq = $cust_pkg->part_pkg->freq;
1262 my $start = $cust_pkg->setup;
1263 #my $end = $cust_pkg->bill; # or time?
1266 unless ( $p->{beginning} ) {
1267 $p->{beginning} = $cust_pkg->last_bill;
1268 $p->{ending} = $end;
1271 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1273 #kinda false laziness with FS::cust_main::bill, but perhaps
1274 #we should really change this bit to DateTime and DateTime::Duration
1276 #change this bit to use Date::Manip? CAREFUL with timezones (see
1277 # mailing list archive)
1278 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1279 (localtime($p->{ending}) )[0,1,2,3,4,5];
1280 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1281 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1283 if ( $freq =~ /^\d+$/ ) {
1285 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1287 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1288 } elsif ( $freq =~ /^(\d+)w$/ ) {
1290 $nmday += $weeks * 7;
1291 $pmday -= $weeks * 7;
1292 } elsif ( $freq =~ /^(\d+)d$/ ) {
1296 } elsif ( $freq =~ /^(\d+)h$/ ) {
1301 return { 'error' => "unparsable frequency: ". $freq };
1304 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1305 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1309 'svcnum' => $p->{svcnum},
1310 'beginning' => $p->{beginning},
1311 'ending' => $p->{ending},
1312 'previous' => ($previous > $start) ? $previous : $start,
1313 'next' => ($next < $end) ? $next : $end,
1314 'header' => $header,
1322 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1323 return { 'error' => $session } if $context eq 'error';
1325 my $search = { 'custnum' => $custnum };
1326 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1327 my $cust_main = qsearchs('cust_main', $search )
1328 or return { 'error' => "unknown custnum $custnum" };
1330 my $status = $cust_main->status;
1331 #false laziness w/ClientAPI/Signup.pm
1333 my $cust_pkg = new FS::cust_pkg ( {
1334 'custnum' => $custnum,
1335 'pkgpart' => $p->{'pkgpart'},
1337 my $error = $cust_pkg->check;
1338 return { 'error' => $error } if $error;
1341 unless ( $p->{'svcpart'} eq 'none' ) {
1345 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1347 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1348 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1349 $svcdb = $part_svc->svcdb;
1351 $svcdb = 'svc_acct';
1353 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1356 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
1357 'svc_domain' => [ qw( domain ) ],
1358 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
1359 'svc_external' => [ qw( id title ) ],
1360 'svc_pbx' => [ qw( id title ) ],
1363 my $svc_x = "FS::$svcdb"->new( {
1364 'svcpart' => $svcpart,
1365 map { $_ => $p->{$_} } @{$fields{$svcdb}}
1368 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1371 while ( length($p->{"snarf_machine$snarfnum"}) ) {
1372 my $acct_snarf = new FS::acct_snarf ( {
1373 'machine' => $p->{"snarf_machine$snarfnum"},
1374 'protocol' => $p->{"snarf_protocol$snarfnum"},
1375 'username' => $p->{"snarf_username$snarfnum"},
1376 '_password' => $p->{"snarf_password$snarfnum"},
1379 push @acct_snarf, $acct_snarf;
1381 $svc_x->child_objects( \@acct_snarf );
1384 my $y = $svc_x->setdefault; # arguably should be in new method
1385 return { 'error' => $y } if $y && !ref($y);
1387 $error = $svc_x->check;
1388 return { 'error' => $error } if $error;
1395 tie my %hash, 'Tie::RefHash';
1396 %hash = ( $cust_pkg => \@svc );
1398 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1399 return { 'error' => $error } if $error;
1401 my $conf = new FS::Conf;
1402 if ( $conf->exists('signup_server-realtime') ) {
1404 my $bill_error = _do_bop_realtime( $cust_main, $status );
1407 $cust_pkg->cancel('quiet'=>1);
1410 $cust_pkg->reexport;
1414 $cust_pkg->reexport;
1417 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1419 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1426 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1427 return { 'error' => $session } if $context eq 'error';
1429 my $search = { 'custnum' => $custnum };
1430 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1431 my $cust_main = qsearchs('cust_main', $search )
1432 or return { 'error' => "unknown custnum $custnum" };
1434 my $status = $cust_main->status;
1435 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1436 or return { 'error' => "unknown package $p->{pkgnum}" };
1439 my $error = FS::cust_pkg::order( $custnum,
1445 my $conf = new FS::Conf;
1446 if ( $conf->exists('signup_server-realtime') ) {
1448 my $bill_error = _do_bop_realtime( $cust_main, $status );
1451 $newpkg[0]->suspend;
1454 $newpkg[0]->reexport;
1458 $newpkg[0]->reexport;
1461 return { error => '', pkgnum => $cust_pkg->pkgnum };
1465 sub order_recharge {
1468 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1469 return { 'error' => $session } if $context eq 'error';
1471 my $search = { 'custnum' => $custnum };
1472 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1473 my $cust_main = qsearchs('cust_main', $search )
1474 or return { 'error' => "unknown custnum $custnum" };
1476 my $status = $cust_main->status;
1477 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1478 or return { 'error' => "unknown service " . $p->{'svcnum'} };
1480 my $svc_x = $cust_svc->svc_x;
1481 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1484 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
1485 qw ( recharge_seconds recharge_upbytes recharge_downbytes
1486 recharge_totalbytes );
1487 my $amount = $part_pkg->option('recharge_amount', 1);
1489 my ($l, $v, $d) = $cust_svc->label; # blah
1490 my $pkg = "Recharge $v";
1492 my $bill_error = $cust_main->charge($amount, $pkg,
1493 "time: $vhash{seconds}, up: $vhash{upbytes}," .
1494 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1495 $part_pkg->taxclass); #meh
1497 my $conf = new FS::Conf;
1498 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1500 $bill_error = _do_bop_realtime( $cust_main, $status );
1505 my $error = $svc_x->recharge (\%vhash);
1506 return { 'error' => $error } if $error;
1510 my $error = $bill_error;
1511 $error ||= $svc_x->recharge (\%vhash);
1512 return { 'error' => $error } if $error;
1515 return { error => '', svc => $cust_svc->part_svc->svc };
1519 sub _do_bop_realtime {
1520 my ($cust_main, $status) = (shift, shift);
1522 my $old_balance = $cust_main->balance;
1524 my $bill_error = $cust_main->bill
1525 || $cust_main->apply_payments_and_credits
1526 || $cust_main->realtime_collect('selfservice' => 1);
1528 if ( $cust_main->balance > $old_balance
1529 && $cust_main->balance > 0
1530 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1531 1 : $status eq 'suspended' ) ) {
1532 #this makes sense. credit is "un-doing" the invoice
1533 my $conf = new FS::Conf;
1534 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1535 'self-service decline',
1536 'reason_type' => $conf->config('signup_credit_type'),
1538 $cust_main->apply_credits( 'order' => 'newest' );
1540 return { 'error' => '_decline', 'bill_error' => $bill_error };
1549 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1550 return { 'error' => $session } if $context eq 'error';
1552 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1553 or return { 'error' => "unknown custnum $custnum" };
1555 my @cust_pkg = sort { $a->bill <=> $b->bill }
1556 grep { $_->part_pkg->freq ne '0' }
1557 $cust_main->ncancelled_pkgs;
1559 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1561 my $total = $cust_main->balance;
1564 my $bill = $_->bill;
1565 $total += $_->part_pkg->base_recur($_, \$bill);
1566 my $renew_date = $_->part_pkg->add_freq($_->bill);
1568 'pkgnum' => $_->pkgnum,
1569 'amount' => sprintf('%.2f', $total),
1570 'bill_date' => $_->bill,
1571 'bill_date_pretty' => time2str('%x', $_->bill),
1572 'renew_date' => $renew_date,
1573 'renew_date_pretty' => time2str('%x', $renew_date),
1574 'expire_date' => $_->expire,
1575 'expire_date_pretty' => time2str('%x', $_->expire),
1580 return { 'dates' => \@array };
1584 sub payment_info_renew_info {
1586 my $renew_info = renew_info($p);
1587 my $payment_info = payment_info($p);
1588 return { %$renew_info,
1596 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1597 return { 'error' => $session } if $context eq 'error';
1599 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1600 or return { 'error' => "unknown custnum $custnum" };
1602 my $date = $p->{'date'};
1606 #freeside-daily -n -d $date fs_daily $custnum
1607 $cust_main->bill_and_collect( 'time' => $date,
1608 'invoice_time' => $now,
1609 'actual_time' => $now,
1610 'check_freq' => '1d',
1613 return { 'error' => '' };
1619 my $session = _cache->get($p->{'session_id'})
1620 or return { 'error' => "Can't resume session" }; #better error message
1622 my $custnum = $session->{'custnum'};
1624 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1625 or return { 'error' => "unknown custnum $custnum" };
1627 my $conf = new FS::Conf;
1629 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1630 or return { 'error' => 'Permission denied' };
1632 my $pkgnum = $p->{'pkgnum'};
1634 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1635 'pkgnum' => $pkgnum, } )
1636 or return { 'error' => "unknown pkgnum $pkgnum" };
1638 my $error = $cust_pkg->suspend(reason => $reasonnum);
1639 return { 'error' => $error };
1645 my $session = _cache->get($p->{'session_id'})
1646 or return { 'error' => "Can't resume session" }; #better error message
1648 my $custnum = $session->{'custnum'};
1650 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1651 or return { 'error' => "unknown custnum $custnum" };
1653 my $pkgnum = $p->{'pkgnum'};
1655 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1656 'pkgnum' => $pkgnum, } )
1657 or return { 'error' => "unknown pkgnum $pkgnum" };
1659 my $error = $cust_pkg->cancel('quiet' => 1);
1660 return { 'error' => $error };
1664 sub provision_phone {
1667 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1669 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1670 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1671 return { 'error' => $session } if $context eq 'error';
1673 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1674 return { 'error' => 'service not found' } unless $svc_phone;
1675 return { 'error' => 'invalid svcnum' }
1676 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1678 $svc_phone->email($p->{'email'})
1679 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1680 $svc_phone->forwarddst($p->{'forwarddst'})
1681 if $svc_phone->forwarddst ne $p->{'forwarddst'}
1682 && $p->{'forwarddst'} =~ /^(\d+|)$/;
1683 return { 'error' => $svc_phone->replace };
1687 unless($p->{'lnp'}) {
1688 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1689 $p->{'lnp_status'} = "portingin";
1690 return _provision( 'FS::svc_phone',
1691 [qw(lnp_desired_due_date lnp_other_provider
1692 lnp_other_provider_account phonenum countrycode lnp_status)],
1693 [qw(phonenum countrycode)],
1700 unless (scalar(@bulkdid)) {
1701 return _provision( 'FS::svc_phone',
1702 [qw(phonenum countrycode)],
1703 [qw(phonenum countrycode)],
1709 # bulk DID order case
1711 foreach my $did ( @bulkdid ) {
1712 $did =~ s/[^0-9]//g;
1713 $error = _provision( 'FS::svc_phone',
1714 [qw(phonenum countrycode)],
1715 [qw(phonenum countrycode)],
1717 'pkgnum' => $p->{'pkgnum'},
1718 'svcpart' => $p->{'svcpart'},
1720 'countrycode' => $p->{'countrycode'},
1721 'session_id' => $p->{'session_id'},
1724 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1726 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1729 sub provision_acct {
1731 warn "provision_acct called\n"
1734 return { 'error' => gettext('passwords_dont_match') }
1735 if $p->{'_password'} ne $p->{'_password2'};
1736 return { 'error' => gettext('empty_password') }
1737 unless length($p->{'_password'});
1739 if ($p->{'domsvc'}) {
1740 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1741 qw ( svcpart pkgnum ) );
1742 return { 'error' => gettext('invalid_domain') }
1743 unless ($domains{$p->{'domsvc'}});
1746 warn "provision_acct calling _provision\n"
1748 _provision( 'FS::svc_acct',
1749 [qw(username _password domsvc)],
1750 [qw(username _password domsvc)],
1756 sub provision_external {
1758 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1759 _provision( 'FS::svc_external',
1768 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1769 warn "_provision called for $class\n"
1772 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1773 return { 'error' => $session } if $context eq 'error';
1775 my $search = { 'custnum' => $custnum };
1776 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1777 my $cust_main = qsearchs('cust_main', $search )
1778 or return { 'error' => "unknown custnum $custnum" };
1780 my $pkgnum = $p->{'pkgnum'};
1782 warn "searching for custnum $custnum pkgnum $pkgnum\n"
1784 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1785 'pkgnum' => $pkgnum,
1787 or return { 'error' => "unknown pkgnum $pkgnum" };
1789 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1791 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1792 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1794 warn "creating $class record\n"
1796 my $svc_x = $class->new( {
1797 'pkgnum' => $p->{'pkgnum'},
1798 'svcpart' => $p->{'svcpart'},
1799 map { $_ => $p->{$_} } @$fields
1801 warn "inserting $class record\n"
1803 my $error = $svc_x->insert;
1806 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1808 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1811 my $return = { 'svc' => $part_svc->svc,
1813 map { $_ => $svc_x->get($_) } @$return_fields
1815 warn "_provision returning ". Dumper($return). "\n"
1824 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1825 return { 'error' => $session } if $context eq 'error';
1827 my $search = { 'custnum' => $custnum };
1828 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1829 my $cust_main = qsearchs('cust_main', $search )
1830 or return { 'error' => "unknown custnum $custnum" };
1832 my $pkgnum = $p->{'pkgnum'};
1834 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1835 'pkgnum' => $pkgnum,
1837 or return { 'error' => "unknown pkgnum $pkgnum" };
1839 my $svcpart = $p->{'svcpart'};
1841 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1842 'svcpart' => $svcpart, } )
1843 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1844 my $part_svc = $pkg_svc->part_svc;
1846 my $conf = new FS::Conf;
1849 'svc' => $part_svc->svc,
1850 'svcdb' => $part_svc->svcdb,
1851 'pkgnum' => $pkgnum,
1852 'svcpart' => $svcpart,
1853 'custnum' => $custnum,
1855 'security_phrase' => 0, #XXX !
1856 'svc_acct_pop' => [], #XXX !
1858 'init_popstate' => '',
1863 small_custview( $cust_main, $conf->config('countrydefault') ),
1867 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
1868 && $ret->{'svcdb'} eq 'svc_phone') {
1869 $ret->{'svcnum'} = $p->{'svcnum'};
1870 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1871 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
1872 $ret->{'email'} = $svc_phone->email;
1873 $ret->{'forwarddst'} = $svc_phone->forwarddst;
1880 sub unprovision_svc {
1883 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1884 return { 'error' => $session } if $context eq 'error';
1886 my $search = { 'custnum' => $custnum };
1887 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1888 my $cust_main = qsearchs('cust_main', $search )
1889 or return { 'error' => "unknown custnum $custnum" };
1891 my $svcnum = $p->{'svcnum'};
1893 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
1894 or return { 'error' => "unknown svcnum $svcnum" };
1896 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1897 unless $cust_svc->cust_pkg->custnum == $custnum;
1899 my $conf = new FS::Conf;
1901 return { 'svc' => $cust_svc->part_svc->svc,
1902 'error' => $cust_svc->cancel,
1904 small_custview( $cust_main, $conf->config('countrydefault') ),
1909 sub myaccount_passwd {
1911 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1912 return { 'error' => $session } if $context eq 'error';
1914 return { 'error' => "New passwords don't match." }
1915 if $p->{'new_password'} ne $p->{'new_password2'};
1917 return { 'error' => 'Enter new password' }
1918 unless length($p->{'new_password'});
1920 #my $search = { 'custnum' => $custnum };
1921 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1922 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1923 my $search = " AND custnum = $1";
1924 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1926 my $svc_acct = qsearchs( {
1927 'table' => 'svc_acct',
1928 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1929 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
1930 'LEFT JOIN cust_main USING ( custnum ) ',
1931 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
1932 'extra_sql' => $search, #important
1934 or return { 'error' => "Service not found" };
1936 $svc_acct->_password($p->{'new_password'});
1937 my $error = $svc_acct->replace();
1939 my($label, $value) = $svc_acct->cust_svc->label;
1941 return { 'error' => $error,
1950 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1951 return { 'error' => $session } if $context eq 'error';
1953 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
1954 FS::TicketSystem->init();
1956 my $conf = new FS::Conf;
1957 my $queue = $p->{'queue'}
1958 || $conf->config('ticket_system-selfservice_queueid')
1959 || $conf->config('ticket_system-default_queueid');
1961 warn "$me create_ticket: creating ticket\n" if $DEBUG;
1962 my $err_or_ticket = FS::TicketSystem->create_ticket(
1963 '', #create RT session based on FS CurrentUser (fs_selfservice)
1965 'custnum' => $custnum,
1966 'svcnum' => $session->{'svcnum'},
1967 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
1970 if ( ref($err_or_ticket) ) {
1971 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
1973 return { 'error' => '',
1974 'ticket_id' => $err_or_ticket->id,
1977 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
1979 return { 'error' => $err_or_ticket };
1987 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1988 return { 'error' => $session } if $context eq 'error';
1990 return { error => 'requested format not implemented' }
1991 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
1993 my $conf = new FS::Conf;
1994 my $age_threshold = 0;
1995 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
1996 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
1998 my $search = { 'custnum' => $custnum };
1999 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2000 my $cust_main = qsearchs('cust_main', $search )
2001 or return { 'error' => "unknown custnum $custnum" };
2003 # does it make more sense to just run one sql query for this instead of all the
2004 # insanity below? would increase performance greately for large data sets?
2006 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2007 my @part_svc = $cust_pkg->part_svc;
2008 foreach my $part_svc ( @part_svc ) {
2009 if($part_svc->svcdb eq 'svc_phone'){
2010 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2011 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2012 push @svc_phone, $cust_pkg_svc->svc_x
2013 if $cust_pkg_svc->date_inserted >= $age_threshold;
2021 my($xls_r,$xls_c) = (0,0);
2024 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2025 if($p->{'format'} eq 'csv') {
2026 $csv = new Text::CSV_XS { 'always_quote' => 1,
2029 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2030 $content .= $csv->string;
2032 elsif($p->{'format'} eq 'xls') {
2033 my $XLS1 = new IO::Scalar \$content;
2034 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2035 or return { 'error' => "Error opening .xls file: $!" };
2036 $xls = $xls_workbook->add_worksheet('DIDs');
2037 foreach ( @fields ) {
2038 $xls->write(0,$xls_c++,$_);
2043 foreach my $svc_phone ( @svc_phone ) {
2044 my @cols = map { $svc_phone->$_ } @fields;
2045 if($p->{'format'} eq 'csv') {
2046 return { 'error' => 'Unable to create CSV' }
2047 unless $csv->combine(@cols);
2048 $content .= $csv->string;
2050 elsif($p->{'format'} eq 'xls') {
2053 $xls->write($xls_r,$xls_c++,$_);
2059 $xls_workbook->close() if $p->{'format'} eq 'xls';
2061 { content => $content, format => $p->{'format'}, };
2066 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2067 return { 'error' => $session } if $context eq 'error';
2069 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2070 FS::TicketSystem->init();
2071 return { 'error' => 'get_ticket configuration error' }
2072 if $FS::TicketSystem::system ne 'RT_Internal';
2074 # check existence and ownership as part of this
2075 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2076 my $rt_session = FS::TicketSystem->session('');
2077 my $Ticket = FS::TicketSystem->get_ticket_object(
2079 ticket_id => $p->{'ticket_id'},
2082 return { 'error' => 'ticket not found' } if !$Ticket;
2084 if ( length( $p->{'subject'} || '' ) ) {
2086 if ( $p->{'subject'} ne $Ticket->Subject ) {
2087 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2088 return { 'error' => "unable to set subject: $msg" } if !$val;
2092 if(length($p->{'reply'})) {
2093 my @err_or_res = FS::TicketSystem->correspond_ticket(
2095 'ticket_id' => $p->{'ticket_id'},
2096 'content' => $p->{'reply'},
2099 return { 'error' => 'unable to reply to ticket' }
2100 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2103 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2104 my $err_or_ticket = FS::TicketSystem->get_ticket(
2106 'ticket_id' => $p->{'ticket_id'},
2109 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2110 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2112 return { 'error' => $err_or_ticket };
2115 my @custs = @{$err_or_ticket->{'custs'}};
2116 my @txns = @{$err_or_ticket->{'txns'}};
2119 # superseded by check in get_ticket_object
2120 #return { 'error' => 'invalid ticket requested' }
2121 #unless grep($_ eq $custnum, @custs);
2123 foreach my $txn ( @txns ) {
2124 push @filtered_txns, $txn
2125 if ($txn->{'type'} eq 'EmailRecord'
2126 || $txn->{'type'} eq 'Correspond'
2127 || $txn->{'type'} eq 'Create');
2130 warn "$me get_ticket: successful: \n"
2132 return { 'error' => '',
2133 'transactions' => \@filtered_txns,
2134 'ticket_fields' => $err_or_ticket->{'fields'},
2135 'ticket_id' => $p->{'ticket_id'},
2139 sub adjust_ticket_priority {
2141 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2142 return { 'error' => $session } if $context eq 'error';
2144 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2145 FS::TicketSystem->init;
2146 my $ss_priority = FS::TicketSystem->selfservice_priority;
2148 return { 'error' => 'adjust_ticket_priority configuration error' }
2149 if $FS::TicketSystem::system ne 'RT_Internal'
2152 my $values = $p->{'values'}; #hashref, id => priority value
2155 foreach my $id (keys %$values) {
2156 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2157 my $Ticket = FS::TicketSystem->get_ticket_object('',
2159 'custnum' => $custnum,
2162 $ticket_error{$id} = 'ticket not found';
2166 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2167 # We're not going to implement it for RT_External.
2168 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2169 my $new_value = $values->{$id};
2170 next if $old_value eq $new_value;
2172 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2174 # AddCustomFieldValue works fine (replacing any existing value) if it's
2175 # a single-valued custom field, which it should be. If it's not, you're
2176 # doing something wrong.
2178 if ( length($new_value) ) {
2179 ($val, $msg) = $Ticket->AddCustomFieldValue(
2180 Field => $ss_priority,
2181 Value => $new_value,
2185 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2186 Field => $ss_priority,
2187 Value => $old_value,
2191 $ticket_error{$id} = $msg if !$val;
2192 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2194 return { 'error' => '',
2195 'ticket_error' => \%ticket_error,
2196 %{ customer_info($p) } # send updated customer info back
2202 sub _custoragent_session_custnum {
2205 my($context, $session, $custnum);
2206 if ( $p->{'session_id'} ) {
2208 $context = 'customer';
2209 $session = _cache->get($p->{'session_id'})
2210 or return ( 'error' => "Can't resume session" ); #better error message
2211 $custnum = $session->{'custnum'};
2213 } elsif ( $p->{'agent_session_id'} ) {
2216 my $agent_cache = new FS::ClientAPI_SessionCache( {
2217 'namespace' => 'FS::ClientAPI::Agent',
2219 $session = $agent_cache->get($p->{'agent_session_id'})
2220 or return ( 'error' => "Can't resume session" ); #better error message
2221 $custnum = $p->{'custnum'};
2225 return ( 'error' => "Can't resume session" ); #better error message
2228 ($context, $session, $custnum);