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 );
9 use Digest::MD5 qw(md5_hex);
12 use Time::Local qw(timelocal_nocheck);
13 use Business::CreditCard;
16 use Spreadsheet::WriteExcel;
17 use OLE::Storage_Lite;
18 use FS::UI::Web::small_custview qw(small_custview); #less doh
20 use FS::UI::bytecount qw( display_bytecount );
23 use FS::Record qw(qsearch qsearchs dbh);
24 use FS::Msgcat qw(gettext);
25 use FS::Misc qw(card_types);
26 use FS::Misc::DateTime qw(parse_datetime);
28 use FS::ClientAPI_SessionCache;
40 use FS::legacy_cust_bill;
41 use FS::cust_main_county;
45 use FS::acct_rt_transaction;
49 $me = '[FS::ClientAPI::MyAccount]';
51 use vars qw( @cust_main_editable_fields );
52 @cust_main_editable_fields = qw(
53 first last company address1 address2 city
54 county state zip country
55 daytime night fax mobile
56 ship_first ship_last ship_company ship_address1 ship_address2 ship_city
57 ship_state ship_zip ship_country
58 ship_daytime ship_night ship_fax ship_mobile
60 payby payinfo payname paystart_month paystart_year payissue payip
61 ss paytype paystate stateid stateid_state
64 BEGIN { #preload to reduce time customer_info takes
65 if ( $FS::TicketSystem::system ) {
66 warn "$me: initializing ticket system\n" if $DEBUG;
67 FS::TicketSystem->init();
72 $cache ||= new FS::ClientAPI_SessionCache( {
73 'namespace' => 'FS::ClientAPI::MyAccount',
80 my($context, $session, $custnum) = _custoragent_session_custnum($p);
81 #return { 'error' => $session } if $context eq 'error';
84 if ( $context eq 'customer' ) {
86 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
89 $sth->execute($custnum) or die $sth->errstr;
91 $agentnum = $sth->fetchrow_arrayref->[0]
92 or die "no agentnum for custnum $custnum";
94 #} elsif ( $context eq 'agent' ) {
95 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
99 my $conf = new FS::Conf;
101 #false laziness w/Signup.pm
103 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
105 if ( $skin_info_cache_agent ) {
107 warn "$me loading cached skin info for agentnum $agentnum\n"
112 warn "$me populating skin info cache for agentnum $agentnum\n"
115 $skin_info_cache_agent = {
116 'agentnum' => $agentnum,
117 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
118 qw( company_name date_format ) ),
119 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
120 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
121 text_color link_color vlink_color hlink_color alink_color
122 font title_color title_align title_size menu_bgcolor menu_fontsize
125 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
126 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
128 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
129 qw( title_left_image title_right_image
130 menu_top_image menu_body_image menu_bottom_image
133 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
134 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
135 qw( head body_header body_footer company_address ) ),
138 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
142 #{ %$skin_info_cache_agent };
143 $skin_info_cache_agent;
150 my $conf = new FS::Conf;
154 'phone_login' => $conf->exists('selfservice_server-phone_login'),
155 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
156 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
157 'banner_image_md5' =>
158 md5_hex($conf->config_binary('selfservice-login_banner_image')),
165 sub login_banner_image {
167 my $conf = new FS::Conf;
168 my $image = $conf->config_binary('selfservice-login_banner_image');
170 'md5' => md5_hex($image),
175 #false laziness w/FS::ClientAPI::passwd::passwd
179 my $conf = new FS::Conf;
182 if ( $p->{'domain'} eq 'svc_phone'
183 && $conf->exists('selfservice_server-phone_login') ) {
185 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
186 return { error => 'Number not found.' } unless $svc_phone;
189 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
190 #return { error => 'Only primary user may log in.' }
191 # if $conf->exists('selfservice_server-primary_only')
192 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
194 return { error => 'Incorrect PIN.' }
195 unless $svc_phone->check_pin($p->{'password'});
201 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
202 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
204 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
205 'domsvc' => $svc_domain->svcnum, }
207 return { error => 'User not found.' } unless $svc_acct;
209 if($conf->exists('selfservice_server-login_svcpart')) {
210 my @svcpart = $conf->config('selfservice_server-login_svcpart');
211 my $svcpart = $svc_acct->cust_svc->svcpart;
212 return { error => 'Invalid user.' }
213 unless grep($_ eq $svcpart, @svcpart);
216 return { error => 'Incorrect password.' }
217 unless $svc_acct->check_password($p->{'password'});
224 'svcnum' => $svc_x->svcnum,
227 my $cust_svc = $svc_x->cust_svc;
228 my $cust_pkg = $cust_svc->cust_pkg;
230 my $cust_main = $cust_pkg->cust_main;
231 $session->{'custnum'} = $cust_main->custnum;
232 if ( $conf->exists('pkg-balances') ) {
233 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
234 $cust_main->ncancelled_pkgs;
235 $session->{'pkgnum'} = $cust_pkg->pkgnum
236 if scalar(@cust_pkg) > 1;
240 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
241 #return { error => 'Only primary user may log in.' }
242 # if $conf->exists('selfservice_server-primary_only')
243 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
244 my $part_pkg = $cust_pkg->part_pkg;
245 return { error => 'Only primary user may log in.' }
246 if $conf->exists('selfservice_server-primary_only')
247 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
251 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
252 } until ( ! defined _cache->get($session_id) ); #just in case
254 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
255 _cache->set( $session_id, $session, $timeout );
257 return { 'error' => '',
258 'session_id' => $session_id,
264 if ( $p->{'session_id'} ) {
265 _cache->remove($p->{'session_id'});
266 return { %{ skin_info($p) }, 'error' => '' };
268 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
275 my($context, $session, $custnum) = _custoragent_session_custnum($p);
276 return { 'error' => $session } if $context eq 'error';
278 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
279 or return { 'error' => "Service not found" };
281 $session->{'svcnum'} = $svc_acct->svcnum;
283 my $conf = new FS::Conf;
284 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
285 _cache->set( $p->{'session_id'}, $session, $timeout );
287 return { 'error' => '' };
291 sub payment_gateway {
293 # takes a cust_main and a cust_payby entry, returns the payment_gateway
294 my $conf = new FS::Conf;
295 my $cust_main = shift;
296 my $cust_payby = shift;
297 my $gatewaynum = $conf->config('selfservice-payment_gateway');
299 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
300 die "configured gatewaynum $gatewaynum not found!" if !$pg;
304 return '' if ! FS::payby->realtime($cust_payby);
305 my $pg = $cust_main->agent->payment_gateway(
306 'method' => FS::payby->payby2bop($cust_payby),
316 my $conf = new FS::Conf;
318 my $info = skin_info($p);
320 use vars qw( $cust_paybys ); #cache for performance
321 unless ( $cust_paybys ) {
323 my %cust_paybys = map { $_ => 1 }
324 map { FS::payby->payby2payment($_) }
325 $conf->config('signup_server-payby');
327 $cust_paybys = [ keys %cust_paybys ];
330 $info->{'cust_paybys'} = $cust_paybys;
332 my($context, $session, $custnum) = _custoragent_session_custnum($p);
333 return { 'error' => $session } if $context eq 'error';
335 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
336 or return { 'error' => "unknown custnum $custnum" };
338 $info->{'hide_payment_fields'} = [
340 my $pg = payment_gateway($cust_main, $_);
341 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
342 } @{ $info->{cust_paybys} }
345 $info->{'self_suspend_reason'} =
346 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
348 $info->{'edit_ticket_subject'} =
349 $conf->exists('ticket_system-selfservice_edit_subject') &&
350 $cust_main->edit_subject;
353 'custnum' => $custnum,
354 'access_pkgnum' => $session->{'pkgnum'},
355 'access_svcnum' => $session->{'svcnum'},
362 my($context, $session, $custnum) = _custoragent_session_custnum($p);
363 return { 'error' => $session } if $context eq 'error';
367 my $conf = new FS::Conf;
368 if ($conf->exists('cust_main-require_address2')) {
369 $return{'require_address2'} = '1';
371 $return{'require_address2'} = '';
374 if ( $FS::TicketSystem::system ) {
375 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
376 FS::TicketSystem->init();
379 if ( $custnum ) { #customer record
381 my $search = { 'custnum' => $custnum };
382 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
383 my $cust_main = qsearchs('cust_main', $search )
384 or return { 'error' => "unknown custnum $custnum" };
386 $return{display_custnum} = $cust_main->display_custnum;
388 if ( $session->{'pkgnum'} ) {
389 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
390 #next_bill_date from cust_pkg?
392 $return{balance} = $cust_main->balance;
393 $return{next_bill_date} = $cust_main->next_bill_date;
394 $return{next_bill_date_pretty} =
395 time2str('%m/%d/%Y', $return{next_bill_date} );
398 my @tickets = $cust_main->tickets;
399 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
400 if ( FS::TicketSystem->selfservice_priority ) {
401 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
405 ($a->{'_selfservice_priority'} eq '') <=>
406 ($b->{'_selfservice_priority'} eq '')
409 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
415 $return{tickets} = \@tickets;
418 unless ( $session->{'pkgnum'} ) {
421 invnum => $_->invnum,
422 date => time2str("%b %o, %Y", $_->_date),
425 } $cust_main->open_cust_bill;
426 $return{open_invoices} = \@open;
428 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
429 my $sth = dbh->prepare($sql) or die dbh->errstr;
430 $sth->execute($custnum) or die $sth->errstr;
431 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
432 $return{'last_invoice_date_pretty'} =
433 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
436 $return{countrydefault} = scalar($conf->config('countrydefault'));
438 $return{small_custview} =
439 small_custview( $cust_main,
440 $return{countrydefault},
441 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
444 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
445 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
447 $return{has_ship_address} = $cust_main->has_ship_address;
448 $return{status} = $cust_main->status;
449 $return{statuscolor} = $cust_main->statuscolor;
451 for (@cust_main_editable_fields) {
452 $return{$_} = $cust_main->get($_);
455 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
456 $return{payinfo} = $cust_main->paymask;
457 @return{'month', 'year'} = $cust_main->paydate_monthyear;
460 $return{'invoicing_list'} =
461 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
462 $return{'postal_invoicing'} =
463 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
465 if (scalar($conf->config('support_packages'))) {
466 my @support_services = ();
467 foreach ($cust_main->support_services) {
468 my $seconds = $_->svc_x->seconds;
469 my $time_remaining = (($seconds < 0) ? '-' : '' ).
470 int(abs($seconds)/3600)."h".
471 sprintf("%02d",(abs($seconds)%3600)/60)."m";
472 my $cust_pkg = $_->cust_pkg;
475 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
476 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
477 push @support_services, { svcnum => $_->svcnum,
478 time => $time_remaining,
483 $return{support_services} = \@support_services;
486 if ( $conf->config('prepayment_discounts-credit_type') ) {
488 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
491 if ( $session->{'svcnum'} ) {
492 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
493 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
494 $return{'svcnum'} = $session->{'svcnum'};
497 } elsif ( $session->{'svcnum'} ) { #no customer record
499 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
500 or die "unknown svcnum";
501 $return{name} = $svc_acct->email;
505 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
509 return { 'error' => '',
510 'custnum' => $custnum,
516 sub customer_info_short {
519 my($context, $session, $custnum) = _custoragent_session_custnum($p);
520 return { 'error' => $session } if $context eq 'error';
524 my $conf = new FS::Conf;
526 if ( $custnum ) { #customer record
528 my $search = { 'custnum' => $custnum };
529 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
530 my $cust_main = qsearchs('cust_main', $search )
531 or return { 'error' => "unknown custnum $custnum" };
533 $return{display_custnum} = $cust_main->display_custnum;
535 $return{countrydefault} = scalar($conf->config('countrydefault'));
537 $return{small_custview} =
538 small_custview( $cust_main,
539 $return{countrydefault},
543 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
544 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
546 $return{payby} = $cust_main->payby;
548 #none of these are terribly expensive if we want 'em...
549 for (@cust_main_editable_fields) {
550 $return{$_} = $cust_main->get($_);
553 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
554 $return{payinfo} = $cust_main->paymask;
555 @return{'month', 'year'} = $cust_main->paydate_monthyear;
558 $return{'invoicing_list'} =
559 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
560 #$return{'postal_invoicing'} =
561 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
563 if ( $session->{'svcnum'} ) {
564 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
565 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
566 $return{'svcnum'} = $session->{'svcnum'};
569 } elsif ( $session->{'svcnum'} ) { #no customer record
571 #uuh, not supproted yet... die?
572 return { 'error' => 'customer_info_short not yet supported as agent' };
576 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
580 return { 'error' => '',
581 'custnum' => $custnum,
586 sub billing_history {
589 my($context, $session, $custnum) = _custoragent_session_custnum($p);
590 return { 'error' => $session } if $context eq 'error';
592 return { 'error' => 'No customer' } unless $custnum;
594 my $search = { 'custnum' => $custnum };
595 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
596 my $cust_main = qsearchs('cust_main', $search )
597 or return { 'error' => "unknown custnum $custnum" };
601 if ( $session->{'pkgnum'} ) {
602 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
603 #next_bill_date from cust_pkg?
604 return { 'error' => 'No history for package' };
607 $return{balance} = $cust_main->balance;
608 $return{next_bill_date} = $cust_main->next_bill_date;
609 $return{next_bill_date_pretty} =
610 time2str('%m/%d/%Y', $return{next_bill_date} );
614 my $conf = new FS::Conf;
616 if ( $conf->exists('selfservice-billing_history-line_items') ) {
618 foreach my $cust_bill ( $cust_main->cust_bill ) {
621 'type' => 'Line item',
622 'description' => $_->desc. ( $_->sdate && $_->edate
623 ? ' '. time2str('%d-%b-%Y', $_->sdate).
624 ' To '. time2str('%d-%b-%Y', $_->edate)
627 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
628 'date' => $cust_bill->_date,
629 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
631 foreach $cust_bill->cust_bill_pkg;
639 'description' => 'Invoice #'. $_->display_invnum,
640 'amount' => sprintf('%.2f', $_->charged ),
642 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
644 foreach $cust_main->cust_bill;
650 'description' => 'Payment', #XXX type
651 'amount' => sprintf('%.2f', 0 - $_->paid ),
653 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
655 foreach $cust_main->cust_pay;
659 'description' => 'Credit', #more info?
660 'amount' => sprintf('%.2f', 0 -$_->amount ),
662 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
664 foreach $cust_main->cust_credit;
668 'description' => 'Refund', #more info? type, like payment?
669 'amount' => $_->refund,
671 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
673 foreach $cust_main->cust_refund;
675 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
677 $return{'history'} = \@history;
685 my $session = _cache->get($p->{'session_id'})
686 or return { 'error' => "Can't resume session" }; #better error message
688 my $custnum = $session->{'custnum'}
689 or return { 'error' => "no customer record" };
691 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
692 or return { 'error' => "unknown custnum $custnum" };
694 my $new = new FS::cust_main { $cust_main->hash };
695 # Avoid accidentally changing the service address.
696 if ( !$new->has_ship_address ) {
697 $new->set( $_ => $new->get($_) )
698 foreach $new->addr_fields;
701 $new->set( $_ => $p->{$_} )
702 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
705 if (exists($p->{'payby'})) {
706 $p->{'payby'} =~ /^([A-Z]{4})$/
707 or return { 'error' => "illegal_payby " . $p->{'payby'} };
711 if ( $payby =~ /^(CARD|DCRD)$/ ) {
713 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
715 if ( $new->payinfo eq $cust_main->paymask ) {
716 $new->payinfo($cust_main->payinfo);
718 $new->payinfo($p->{'payinfo'});
721 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
723 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
726 $p->{'payinfo1'} =~ /^([\dx]+)$/
727 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
729 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
730 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
732 $payinfo = $payinfo1. '@'. $payinfo2;
734 $new->payinfo( ($payinfo eq $cust_main->paymask)
735 ? $cust_main->payinfo
739 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
741 } elsif ( $payby =~ /^(BILL)$/ ) {
743 } elsif ( $payby ) { #notyet ready
744 return { 'error' => "unknown payby $payby" };
748 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
749 #false laziness with httemplate/edit/process/cust_main.cgi
750 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
751 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
753 @invoicing_list = $cust_main->invoicing_list;
756 my $error = $new->replace($cust_main, \@invoicing_list);
757 return { 'error' => $error } if $error;
760 return { 'error' => '' };
765 my $session = _cache->get($p->{'session_id'})
766 or return { 'error' => "Can't resume session" }; #better error message
772 my $conf = new FS::Conf;
773 use vars qw($payment_info); #cache for performance
774 unless ( $payment_info ) {
776 my %states = map { $_->state => 1 }
777 qsearch('cust_main_county', {
778 'country' => $conf->config('countrydefault') || 'US'
781 my %cust_paybys = map { $_ => 1 }
782 map { FS::payby->payby2payment($_) }
783 $conf->config('signup_server-payby');
785 my @cust_paybys = keys %cust_paybys;
789 #list all counties/states/countries
790 'cust_main_county' =>
791 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
793 #shortcut for one-country folks
795 [ sort { $a cmp $b } keys %states ],
797 'card_types' => card_types(),
799 'paytypes' => [ @FS::cust_main::paytypes ],
801 'paybys' => [ $conf->config('signup_server-payby') ],
802 'cust_paybys' => \@cust_paybys,
804 'stateid_label' => FS::Msgcat::_gettext('stateid'),
805 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
807 'show_ss' => $conf->exists('show_ss'),
808 'show_stateid' => $conf->exists('show_stateid'),
809 'show_paystate' => $conf->exists('show_bankstate'),
811 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
813 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
822 my %return = %$payment_info;
824 my $custnum = $session->{'custnum'};
826 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
827 or return { 'error' => "unknown custnum $custnum" };
829 $return{'hide_payment_fields'} = [
831 my $pg = payment_gateway($cust_main, $_);
832 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
833 } @{ $return{cust_paybys} }
836 $return{balance} = $cust_main->balance; #XXX pkg-balances?
838 $return{payname} = $cust_main->payname
839 || ( $cust_main->first. ' '. $cust_main->get('last') );
841 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
843 $return{payby} = $cust_main->payby;
844 $return{stateid_state} = $cust_main->stateid_state;
846 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
847 $return{card_type} = cardtype($cust_main->payinfo);
848 $return{payinfo} = $cust_main->paymask;
850 @return{'month', 'year'} = $cust_main->paydate_monthyear;
854 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
855 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
856 $return{payinfo1} = $payinfo1;
857 $return{payinfo2} = $payinfo2;
858 $return{paytype} = $cust_main->paytype;
859 $return{paystate} = $cust_main->paystate;
860 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
863 if ( $conf->config('prepayment_discounts-credit_type') ) {
865 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
868 #doubleclick protection
870 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
872 return { 'error' => '',
878 #some false laziness with httemplate/process/payment.cgi - look there for
879 #ACH and CVV support stuff
881 sub validate_payment {
884 my $session = _cache->get($p->{'session_id'})
885 or return { 'error' => "Can't resume session" }; #better error message
887 my $custnum = $session->{'custnum'};
889 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
890 or return { 'error' => "unknown custnum $custnum" };
892 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
893 or return { 'error' => gettext('illegal_amount') };
895 return { error => 'Amount must be greater than 0' } unless $amount > 0;
897 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
898 #changing the hidden form values
899 my $conf = new FS::Conf;
900 my $fee_display = $conf->config('selfservice_process-display') || 'add';
901 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
902 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
903 if ( $fee_display eq 'add'
905 and ! $fee_skip_first || scalar($cust_main->cust_pay)
908 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
909 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
912 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
913 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
914 my $discount_term = $1;
916 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
917 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
920 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
921 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
924 $p->{'payby'} ||= 'CARD';
925 $p->{'payby'} =~ /^([A-Z]{4})$/
926 or return { 'error' => "illegal_payby " . $p->{'payby'} };
929 #false laziness w/process/payment.cgi
932 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
934 $p->{'payinfo1'} =~ /^([\dx]+)$/
935 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
937 $p->{'payinfo2'} =~ /^([\dx]+)$/
938 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
940 $payinfo = $payinfo1. '@'. $payinfo2;
942 $payinfo = $cust_main->payinfo
943 if $cust_main->paymask eq $payinfo;
945 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
947 $payinfo = $p->{'payinfo'};
949 #more intelligent matching will be needed here if you change
950 #card_masking_method and don't remove existing paymasks
951 $payinfo = $cust_main->payinfo
952 if $cust_main->paymask eq $payinfo;
955 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
956 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
960 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
961 return { 'error' => gettext('unknown_card_type') }
962 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
964 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
965 if ( cardtype($payinfo) eq 'American Express card' ) {
966 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
967 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
970 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
971 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
977 die "unknown payby $payby";
981 'CARD' => [ qw( paystart_month paystart_year payissue payip
982 address1 address2 city state zip country ) ],
983 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
987 $card_type = cardtype($payinfo) if $payby eq 'CARD';
990 'cust_main' => $cust_main, #XXX or just custnum??
993 'payinfo' => $payinfo,
994 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
995 'card_type' => $card_type,
996 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
997 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
998 'month' => $p->{'month'},
999 'year' => $p->{'year'},
1000 'payname' => $payname,
1001 'paybatch' => $paybatch, #this doesn't actually do anything
1002 'paycvv' => $paycvv,
1003 'payname' => $payname,
1004 'discount_term' => $discount_term,
1005 'pkgnum' => $session->{'pkgnum'},
1006 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1016 my $validate = validate_payment($p);
1017 return $validate if $validate->{'error'};
1019 my $conf = new FS::Conf;
1020 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1021 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1023 +{ map { $_=>$validate->{$_} }
1024 qw( card_type paymask payname paydate_pretty month year amount
1025 address1 address2 city state zip country
1031 sub process_stored_payment {
1034 my $session_id = $p->{'session_id'};
1036 my $payment_info = _cache->get( "payment_$session_id" )
1037 or return { 'error' => "Can't resume session" }; #better error message
1039 do_process_payment($payment_info);
1043 sub process_payment {
1046 my $payment_info = validate_payment($p);
1047 return $payment_info if $payment_info->{'error'};
1049 do_process_payment($payment_info);
1053 sub do_process_payment {
1054 my $validate = shift;
1056 my $cust_main = $validate->{'cust_main'};
1058 my $amount = delete $validate->{'amount'};
1061 my $payby = delete $validate->{'payby'};
1063 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1066 'paynum_ref' => \$paynum,
1069 return { 'error' => $error } if $error;
1071 #no error, so order the fee package if applicable...
1072 my $conf = new FS::Conf;
1073 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1074 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1076 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1078 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1080 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1081 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1084 #and generate an invoice for it now too
1085 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1086 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1091 $cust_main->apply_payments;
1093 if ( $validate->{'save'} ) {
1094 my $new = new FS::cust_main { $cust_main->hash };
1095 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1096 $new->set( $_ => $validate->{$_} )
1097 foreach qw( payname paystart_month paystart_year payissue payip );
1098 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1100 # Avoid accidentally changing the service address.
1101 if ( !$new->has_ship_address ) {
1102 $new->set( "ship_$_" => $new->get($_) )
1103 foreach $new->addr_fields;
1105 $new->set( $_ => $validate->{$_} )
1106 foreach qw(address1 address2 city state country zip);
1108 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1109 $new->set( $_ => $validate->{$_} )
1110 foreach qw( payname payip paytype paystate
1111 stateid stateid_state );
1112 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1114 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1115 $new->set( 'paydate' => $validate->{'paydate'} );
1116 my $error = $new->replace($cust_main);
1118 #no, this causes customers to process their payments again
1119 #return { 'error' => $error };
1120 #XXX just warn verosely for now so i can figure out how these happen in
1121 # the first place, eventually should redirect them to the "change
1122 #address" page but indicate the payment did process??
1123 delete($validate->{'payinfo'}); #don't want to log this!
1124 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1125 "NEW: ". Dumper($new)."\n".
1126 "OLD: ". Dumper($cust_main)."\n".
1127 "PACKET: ". Dumper($validate)."\n";
1135 my $receipt_html = '';
1137 # currently supported for realtime CC only; send receipt data to SS
1138 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1141 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1144 <TD ALIGN="right">Payment#</TD>
1145 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1149 <TD ALIGN="right">Date</TD>
1151 <TD BGCOLOR="#FFFFFF"><B>! .
1152 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1158 <TD ALIGN="right">Amount</TD>
1159 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1164 <TD ALIGN="right">Payment method</TD>
1165 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1176 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1180 'amount' => sprintf('%.2f', $cust_pay->paid),
1181 'date' => $cust_pay->_date,
1182 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1183 'time_pretty' => time2str('%T', $cust_pay->_date),
1184 'auth_num' => $auth,
1185 'order_num' => $order,
1186 'receipt_html' => $receipt_html,
1193 'receipt_html' => '',
1200 sub realtime_collect {
1203 my $session = _cache->get($p->{'session_id'})
1204 or return { 'error' => "Can't resume session" }; #better error message
1206 my $custnum = $session->{'custnum'};
1208 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1209 or return { 'error' => "unknown custnum $custnum" };
1212 if ( $p->{'amount'} ) {
1213 $amount = $p->{'amount'};
1215 elsif ( $session->{'pkgnum'} ) {
1216 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1219 $amount = $cust_main->balance;
1222 my $error = $cust_main->realtime_collect(
1223 'method' => $p->{'method'},
1224 'amount' => $amount,
1225 'pkgnum' => $session->{'pkgnum'},
1226 'session_id' => $p->{'session_id'},
1230 return { 'error' => $error } unless ref( $error );
1232 return { 'error' => '', amount => $amount, %$error };
1235 sub process_payment_order_pkg {
1238 my $hr = process_payment($p);
1239 return $hr if $hr->{'error'};
1244 sub process_payment_order_renew {
1247 my $hr = process_payment($p);
1248 return $hr if $hr->{'error'};
1253 sub process_prepay {
1257 my $session = _cache->get($p->{'session_id'})
1258 or return { 'error' => "Can't resume session" }; #better error message
1262 my $custnum = $session->{'custnum'};
1264 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1265 or return { 'error' => "unknown custnum $custnum" };
1267 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1268 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1276 return { 'error' => $error } if $error;
1278 return { 'error' => '',
1279 'amount' => $amount,
1280 'seconds' => $seconds,
1281 'duration' => duration_exact($seconds),
1282 'upbytes' => $upbytes,
1283 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1284 'downbytes' => $downbytes,
1285 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1286 'totalbytes'=> $totalbytes,
1287 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1294 my $session = _cache->get($p->{'session_id'})
1295 or return { 'error' => "Can't resume session" }; #better error message
1297 my $custnum = $session->{'custnum'};
1299 my $invnum = $p->{'invnum'};
1301 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1302 'custnum' => $custnum } )
1303 or return { 'error' => "Can't find invnum" };
1307 return { 'error' => '',
1308 'invnum' => $invnum,
1309 'invoice_text' => join('', $cust_bill->print_text ),
1310 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1317 my $session = _cache->get($p->{'session_id'})
1318 or return { 'error' => "Can't resume session" }; #better error message
1320 my $custnum = $session->{'custnum'};
1322 my $invnum = $p->{'invnum'};
1324 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1325 'custnum' => $custnum } )
1326 or return { 'error' => "Can't find invnum" };
1330 return { 'error' => '',
1331 'invnum' => $invnum,
1332 'invoice_pdf' => $cust_bill->print_pdf({
1333 'unsquelch_cdr' => 1,
1334 'locale' => $p->{'locale'},
1340 sub legacy_invoice {
1342 my $session = _cache->get($p->{'session_id'})
1343 or return { 'error' => "Can't resume session" }; #better error message
1345 my $custnum = $session->{'custnum'};
1347 my $legacyinvnum = $p->{'legacyinvnum'};
1350 'legacyinvnum' => $legacyinvnum,
1351 'custnum' => $custnum,
1354 my $legacy_cust_bill =
1355 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1356 || qsearchs('legacy_cust_bill', \%hash )
1357 or return { 'error' => "Can't find legacyinvnum" };
1361 return { 'error' => '',
1362 'legacyinvnum' => $legacyinvnum,
1363 'legacyid' => $legacy_cust_bill->legacyid,
1364 'invoice_html' => $legacy_cust_bill->content_html,
1369 sub legacy_invoice_pdf {
1371 my $session = _cache->get($p->{'session_id'})
1372 or return { 'error' => "Can't resume session" }; #better error message
1374 my $custnum = $session->{'custnum'};
1376 my $legacyinvnum = $p->{'legacyinvnum'};
1378 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1379 'legacyinvnum' => $legacyinvnum,
1380 'custnum' => $custnum,
1381 }) or return { 'error' => "Can't find legacyinvnum" };
1385 return { 'error' => '',
1386 'legacyinvnum' => $legacyinvnum,
1387 'legacyid' => $legacy_cust_bill->legacyid,
1388 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1396 #sessioning for this? how do we get the session id to the backend invoice
1397 # template so it can add it to the link, blah
1400 if ( $p->{'invnum'} ) {
1401 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1402 or return { 'error' => 'unknown invnum' };
1403 $agentnum = $cust_bill->cust_main->agentnum;
1406 my $templatename = $p->{'template'} || $p->{'templatename'};
1408 #false laziness-ish w/view/cust_bill-logo.cgi
1410 my $conf = new FS::Conf;
1411 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1412 $templatename = "_$1";
1417 my $filename = "logo$templatename.png";
1419 return { 'error' => '',
1420 'logo' => $conf->config_binary($filename, $agentnum),
1421 'content_type' => 'image/png', #should allow gif, jpg too
1428 my $session = _cache->get($p->{'session_id'})
1429 or return { 'error' => "Can't resume session" }; #better error message
1431 my $custnum = $session->{'custnum'};
1433 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1434 or return { 'error' => "unknown custnum $custnum" };
1436 my $conf = new FS::Conf;
1438 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1440 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1444 return { 'error' => '',
1445 'balance' => $cust_main->balance,
1448 my $owed = $_->owed;
1450 +{ 'invnum' => $_->invnum,
1451 '_date' => $_->_date,
1452 'date' => time2str("%b %o, %Y", $_->_date),
1453 'date_short' => time2str("%m-%d-%Y", $_->_date),
1454 'previous' => sprintf('%.2f', ($_->previous)[0]),
1455 'charged' => sprintf('%.2f', $_->charged),
1456 'owed' => sprintf('%.2f', $owed),
1457 'balance' => sprintf('%.2f', $balance),
1462 'legacy_invoices' => [
1464 +{ 'legacyinvnum' => $_->legacyinvnum,
1465 'legacyid' => $_->legacyid,
1466 '_date' => $_->_date,
1467 'date' => time2str("%b %o, %Y", $_->_date),
1468 'date_short' => time2str("%m-%d-%Y", $_->_date),
1469 'charged' => sprintf('%.2f', $_->charged),
1470 'has_content' => ( length($_->content_pdf)
1471 || length($_->content_html) ),
1481 my $session = _cache->get($p->{'session_id'})
1482 or return { 'error' => "Can't resume session" }; #better error message
1484 my $custnum = $session->{'custnum'};
1486 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1487 or return { 'error' => "unknown custnum $custnum" };
1489 my @errors = $cust_main->cancel( 'quiet'=>1 );
1491 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1493 return { 'error' => $error };
1500 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1501 return { 'error' => $session } if $context eq 'error';
1503 my $search = { 'custnum' => $custnum };
1504 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1505 my $cust_main = qsearchs('cust_main', $search )
1506 or return { 'error' => "unknown custnum $custnum" };
1508 my $conf = new FS::Conf;
1510 # the duplication below is necessary:
1511 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1512 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1513 # non-backwards-compatible change breaking the software of anyone using the API
1514 # instead of the stock selfservice
1515 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1516 if( $conf->exists('selfservice_server-view-wholesale') ) {
1517 return { 'svcnum' => $session->{'svcnum'},
1518 'custnum' => $custnum,
1519 'cust_pkg' => [ map {
1521 part_pkg => [ map $_->hashref, $_->part_pkg ],
1523 [ map $_->hashref, $_->available_part_svc ],
1525 [ map { my $ref = { $_->hash,
1526 label => [ $_->label ],
1528 $ref->{_password} = $_->svc_x->_password
1529 if $context eq 'agent'
1530 && $conf->exists('agent-showpasswords')
1531 && $_->part_svc->svcdb eq 'svc_acct';
1536 } $cust_main->cust_pkg
1539 small_custview( $cust_main, $conf->config('countrydefault') ),
1540 'wholesale_view' => 1,
1541 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1542 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1543 'lnp' => $conf->exists('svc_phone-lnp'),
1547 { 'svcnum' => $session->{'svcnum'},
1548 'custnum' => $custnum,
1549 'cust_pkg' => [ map {
1550 my $primary_cust_svc = $_->primary_cust_svc;
1553 pkg_label => $_->pkg_label,
1554 status => $_->status,
1556 [ map $_->hashref, $_->available_part_svc ],
1558 [ map { my $ref = { $_->hash,
1559 label => [ $_->label ],
1561 $ref->{_password} = $_->svc_x->_password
1562 if $context eq 'agent'
1563 && $conf->exists('agent-showpasswords')
1564 && $_->part_svc->svcdb eq 'svc_acct';
1565 $ref->{svchash} = { $_->svc_x->hash } if
1566 $_->part_svc->svcdb eq 'svc_phone';
1567 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1568 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1574 ? { $primary_cust_svc->hash,
1575 label => [ $primary_cust_svc->label ],
1576 finger => $primary_cust_svc->svc_x->finger, #uuh
1577 $primary_cust_svc->part_svc->hash,
1581 } $cust_main->ncancelled_pkgs
1584 small_custview( $cust_main, $conf->config('countrydefault') ),
1592 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1593 return { 'error' => $session } if $context eq 'error';
1595 my $search = { 'custnum' => $custnum };
1596 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1597 my $cust_main = qsearchs('cust_main', $search )
1598 or return { 'error' => "unknown custnum $custnum" };
1600 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1601 if ( ! $pkgnum && $p->{'svcnum'} ) {
1602 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1603 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1607 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1608 foreach my $cust_pkg ( $p->{'ncancelled'}
1609 ? $cust_main->ncancelled_pkgs
1610 : $cust_main->unsuspended_pkgs ) {
1611 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1612 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1615 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1617 if ( $p->{'svcdb'} ) {
1618 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1620 : ref($p->{'svcdb'}) eq 'ARRAY'
1621 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1622 : { $p->{'svcdb'} => 1 };
1623 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1626 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1629 my $conf = new FS::Conf;
1632 'svcnum' => $session->{'svcnum'},
1633 'custnum' => $custnum,
1634 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1635 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1638 my $svc_x = $_->svc_x;
1639 my($label, $value) = $_->label;
1640 my $part_svc = $_->part_svc;
1641 my $svcdb = $part_svc->svcdb;
1642 my $cust_pkg = $_->cust_pkg;
1643 my $part_pkg = $cust_pkg->part_pkg;
1646 'svcnum' => $_->svcnum,
1647 'display_svcnum' => $_->display_svcnum,
1651 'pkg_label' => $cust_pkg->pkg_label,
1652 'pkg_status' => $cust_pkg->status,
1653 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1656 if ( $svcdb eq 'svc_acct' ) {
1659 'username' => $svc_x->username,
1660 'email' => $svc_x->email,
1661 'finger' => $svc_x->finger,
1662 'seconds' => $svc_x->seconds,
1663 'upbytes' => display_bytecount($svc_x->upbytes),
1664 'downbytes' => display_bytecount($svc_x->downbytes),
1665 'totalbytes' => display_bytecount($svc_x->totalbytes),
1667 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1668 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1669 'recharge_upbytes' =>
1670 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1671 'recharge_downbytes' =>
1672 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1673 'recharge_totalbytes' =>
1674 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1678 } elsif ( $svcdb eq 'svc_dsl' ) {
1679 $hash{'phonenum'} = $svc_x->phonenum;
1680 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1681 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1682 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1685 $hash{'name'} = $cust_main->name;
1688 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1702 sub _customer_svc_x {
1703 my($custnum, $svcnum, $table) = (shift, shift, shift);
1704 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1706 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1707 my $search = " AND custnum = $1";
1708 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1711 'table' => ($table || 'svc_acct'),
1712 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1713 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1714 #'LEFT JOIN cust_main USING ( custnum ) ',
1715 'hashref' => $hashref,
1716 'extra_sql' => $search, #important
1721 sub svc_status_html {
1724 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1725 return { 'error' => $session } if $context eq 'error';
1727 #XXX only svc_dsl for now
1728 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1729 or return { 'error' => "Service not found" };
1731 my $html = $svc_x->getstatus_html;
1733 return { 'html' => $html };
1737 sub svc_status_hash {
1740 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1741 return { 'error' => $session } if $context eq 'error';
1743 #XXX only svc_acct for now
1744 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1745 or return { 'error' => "Service not found" };
1747 my ( $html, $hashref ) = $svc_x->export_getstatus;
1752 sub set_svc_status_hash {
1755 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1756 return { 'error' => $session } if $context eq 'error';
1758 #XXX only svc_acct for now
1759 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1760 or return { 'error' => "Service not found" };
1762 warn "set_svc_status_hash ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1764 my $error = $svc_x->export_setstatus($p); #$p? returns error?
1765 return { 'error' => $error } if $error;
1767 return {}; #? { 'error' => '' }
1772 sub acct_forward_info {
1775 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1776 return { 'error' => $session } if $context eq 'error';
1778 my $svc_forward = _customer_svc_x( $custnum,
1779 { 'srcsvc' => $p->{'svcnum'} },
1782 or return { 'error' => '',
1786 return { 'error' => '',
1787 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1792 sub process_acct_forward {
1794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1795 return { 'error' => $session } if $context eq 'error';
1797 my $old = _customer_svc_x( $custnum,
1798 { 'srcsvc' => $p->{'svcnum'} },
1802 if ( $p->{'dst'} eq '' ) {
1804 my $error = $old->delete;
1805 return { 'error' => $error };
1807 return { 'error' => '' };
1810 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1811 'dst' => $p->{'dst'},
1816 $new->svcnum($old->svcnum);
1817 my $cust_svc = $old->cust_svc;
1818 $new->svcpart($old->svcpart);
1819 $new->pkgnuym($old->pkgnum);
1820 $error = $new->replace($old);
1822 my $conf = new FS::Conf;
1823 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1825 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1826 or return { 'error' => 'No service' }; #how would we even get here?
1828 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1830 $error = $new->insert;
1833 return { 'error' => $error };
1837 sub list_dsl_devices {
1840 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1841 return { 'error' => $session } if $context eq 'error';
1843 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1844 or return { 'error' => "Service not found" };
1847 'devices' => [ map {
1848 +{ 'mac_addr' => $_->mac_addr };
1849 } $svc_dsl->dsl_device
1855 sub add_dsl_device {
1858 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1859 return { 'error' => $session } if $context eq 'error';
1861 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1862 or return { 'error' => "Service not found" };
1864 return { 'error' => 'No MAC address supplied' }
1865 unless length($p->{'mac_addr'});
1867 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1868 'mac_addr' => scalar($p->{'mac_addr'}),
1870 my $error = $dsl_device->insert;
1871 return { 'error' => $error };
1875 sub delete_dsl_device {
1878 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1879 return { 'error' => $session } if $context eq 'error';
1881 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1882 or return { 'error' => "Service not found" };
1884 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
1885 'mac_addr' => scalar($p->{'mac_addr'}),
1888 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1890 my $error = $dsl_device->delete;
1891 return { 'error' => $error };
1897 _usage_details( \&_port_graph, $p,
1898 'svcdb' => 'svc_port',
1903 my($svc_port, $begin, $end) = @_;
1905 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1906 push @usage, { 'png' => $pngOrError };
1910 sub _list_svc_usage {
1911 my($svc_acct, $begin, $end) = @_;
1913 foreach my $part_export (
1914 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1915 qw( sqlradius sqlradius_withdomain )
1917 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1922 sub list_svc_usage {
1923 _usage_details(\&_list_svc_usage, @_);
1926 sub _list_support_usage {
1927 my($svc_acct, $begin, $end) = @_;
1929 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1930 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1932 push @usage, { 'seconds' => $_->seconds,
1933 'support' => $_->support,
1934 '_date' => $_->_date,
1935 'id' => $_->transaction_id,
1936 'creator' => $_->creator,
1937 'subject' => $_->subject,
1938 'status' => $_->status,
1939 'ticketid' => $_->ticketid,
1945 sub list_support_usage {
1946 _usage_details(\&_list_support_usage, @_);
1949 sub _list_cdr_usage {
1950 # XXX CDR type support...
1951 my($svc_phone, $begin, $end, %opt) = @_;
1952 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
1953 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1956 sub list_cdr_usage {
1958 _usage_details( \&_list_cdr_usage, $p,
1959 'svcdb' => 'svc_phone',
1963 sub _usage_details {
1964 my($callback, $p, %opt) = @_;
1966 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1967 return { 'error' => $session } if $context eq 'error';
1969 my $search = { 'svcnum' => $p->{'svcnum'} };
1970 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1972 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1974 my $svc_x = qsearchs( $svcdb, $search );
1975 return { 'error' => 'No service selected in list_svc_usage' }
1978 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1979 my $freq = $cust_pkg->part_pkg->freq;
1982 if ( $svcdb eq 'svc_phone' ) {
1983 my $format = $cust_pkg->part_pkg->option('output_format') || '';
1984 $format = '' if $format =~ /^sum_/;
1985 # sensible default if there is no format or it's a summary format
1986 if ( $cust_pkg->part_pkg->plan eq 'voip_inbound' ) {
1987 $format ||= 'source_default';
1988 $callback_opt{inbound} = 1;
1991 $format ||= 'default';
1994 $callback_opt{format} = $format;
1995 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
1998 my $start = $cust_pkg->setup;
1999 #my $end = $cust_pkg->bill; # or time?
2002 unless ( $p->{beginning} ) {
2003 $p->{beginning} = $cust_pkg->last_bill;
2004 $p->{ending} = $end;
2007 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2011 #kinda false laziness with FS::cust_main::bill, but perhaps
2012 #we should really change this bit to DateTime and DateTime::Duration
2014 #change this bit to use Date::Manip? CAREFUL with timezones (see
2015 # mailing list archive)
2016 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2017 (localtime($p->{ending}) )[0,1,2,3,4,5];
2018 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2019 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2021 if ( $freq =~ /^\d+$/ ) {
2023 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2025 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2026 } elsif ( $freq =~ /^(\d+)w$/ ) {
2028 $nmday += $weeks * 7;
2029 $pmday -= $weeks * 7;
2030 } elsif ( $freq =~ /^(\d+)d$/ ) {
2034 } elsif ( $freq =~ /^(\d+)h$/ ) {
2039 return { 'error' => "unparsable frequency: ". $freq };
2042 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2043 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2047 'svcnum' => $p->{svcnum},
2048 'beginning' => $p->{beginning},
2049 'ending' => $p->{ending},
2050 'previous' => ($previous > $start) ? $previous : $start,
2051 'next' => ($next < $end) ? $next : $end,
2052 'header' => $header,
2060 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2061 return { 'error' => $session } if $context eq 'error';
2063 my $search = { 'custnum' => $custnum };
2064 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2065 my $cust_main = qsearchs('cust_main', $search )
2066 or return { 'error' => "unknown custnum $custnum" };
2068 my $status = $cust_main->status;
2069 #false laziness w/ClientAPI/Signup.pm
2071 my $cust_pkg = new FS::cust_pkg ( {
2072 'custnum' => $custnum,
2073 'pkgpart' => $p->{'pkgpart'},
2075 my $error = $cust_pkg->check;
2076 return { 'error' => $error } if $error;
2079 unless ( $p->{'svcpart'} eq 'none' ) {
2083 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2085 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2086 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2087 $svcdb = $part_svc->svcdb;
2089 $svcdb = 'svc_acct';
2091 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2094 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2095 'svc_domain' => [ qw( domain ) ],
2096 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2097 'svc_external' => [ qw( id title ) ],
2098 'svc_pbx' => [ qw( id title ) ],
2101 my $svc_x = "FS::$svcdb"->new( {
2102 'svcpart' => $svcpart,
2103 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2106 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2109 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2110 my $acct_snarf = new FS::acct_snarf ( {
2111 'machine' => $p->{"snarf_machine$snarfnum"},
2112 'protocol' => $p->{"snarf_protocol$snarfnum"},
2113 'username' => $p->{"snarf_username$snarfnum"},
2114 '_password' => $p->{"snarf_password$snarfnum"},
2117 push @acct_snarf, $acct_snarf;
2119 $svc_x->child_objects( \@acct_snarf );
2122 my $y = $svc_x->setdefault; # arguably should be in new method
2123 return { 'error' => $y } if $y && !ref($y);
2125 $error = $svc_x->check;
2126 return { 'error' => $error } if $error;
2133 tie my %hash, 'Tie::RefHash';
2134 %hash = ( $cust_pkg => \@svc );
2136 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2137 return { 'error' => $error } if $error;
2139 my $conf = new FS::Conf;
2140 if ( $conf->exists('signup_server-realtime') ) {
2142 my $bill_error = _do_bop_realtime( $cust_main, $status );
2145 $cust_pkg->cancel('quiet'=>1);
2148 $cust_pkg->reexport;
2152 $cust_pkg->reexport;
2155 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2157 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2164 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2165 return { 'error' => $session } if $context eq 'error';
2167 my $search = { 'custnum' => $custnum };
2168 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2169 my $cust_main = qsearchs('cust_main', $search )
2170 or return { 'error' => "unknown custnum $custnum" };
2172 my $status = $cust_main->status;
2173 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2174 or return { 'error' => "unknown package $p->{pkgnum}" };
2177 my $error = FS::cust_pkg::order( $custnum,
2183 my $conf = new FS::Conf;
2184 if ( $conf->exists('signup_server-realtime') ) {
2186 my $bill_error = _do_bop_realtime( $cust_main, $status );
2189 $newpkg[0]->suspend;
2192 $newpkg[0]->reexport;
2196 $newpkg[0]->reexport;
2199 return { error => '', pkgnum => $cust_pkg->pkgnum };
2203 sub order_recharge {
2206 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2207 return { 'error' => $session } if $context eq 'error';
2209 my $search = { 'custnum' => $custnum };
2210 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2211 my $cust_main = qsearchs('cust_main', $search )
2212 or return { 'error' => "unknown custnum $custnum" };
2214 my $status = $cust_main->status;
2215 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2216 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2218 my $svc_x = $cust_svc->svc_x;
2219 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2222 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2223 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2224 recharge_totalbytes );
2225 my $amount = $part_pkg->option('recharge_amount', 1);
2227 my ($l, $v, $d) = $cust_svc->label; # blah
2228 my $pkg = "Recharge $v";
2230 my $bill_error = $cust_main->charge($amount, $pkg,
2231 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2232 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2233 $part_pkg->taxclass); #meh
2235 my $conf = new FS::Conf;
2236 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2238 $bill_error = _do_bop_realtime( $cust_main, $status );
2243 my $error = $svc_x->recharge (\%vhash);
2244 return { 'error' => $error } if $error;
2248 my $error = $bill_error;
2249 $error ||= $svc_x->recharge (\%vhash);
2250 return { 'error' => $error } if $error;
2253 return { error => '', svc => $cust_svc->part_svc->svc };
2257 sub _do_bop_realtime {
2258 my ($cust_main, $status) = (shift, shift);
2260 my $old_balance = $cust_main->balance;
2262 my $bill_error = $cust_main->bill
2263 || $cust_main->apply_payments_and_credits
2264 || $cust_main->realtime_collect('selfservice' => 1);
2266 if ( $cust_main->balance > $old_balance
2267 && $cust_main->balance > 0
2268 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2269 1 : $status eq 'suspended' ) ) {
2270 #this makes sense. credit is "un-doing" the invoice
2271 my $conf = new FS::Conf;
2272 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2273 'self-service decline',
2274 'reason_type' => $conf->config('signup_credit_type'),
2276 $cust_main->apply_credits( 'order' => 'newest' );
2278 return { 'error' => '_decline', 'bill_error' => $bill_error };
2287 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2288 return { 'error' => $session } if $context eq 'error';
2290 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2291 or return { 'error' => "unknown custnum $custnum" };
2293 my @cust_pkg = sort { $a->bill <=> $b->bill }
2294 grep { $_->part_pkg->freq ne '0' }
2295 $cust_main->ncancelled_pkgs;
2297 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2299 my $total = $cust_main->balance;
2302 my $bill = $_->bill;
2303 $total += $_->part_pkg->base_recur($_, \$bill);
2304 my $renew_date = $_->part_pkg->add_freq($_->bill);
2306 'pkgnum' => $_->pkgnum,
2307 'amount' => sprintf('%.2f', $total),
2308 'bill_date' => $_->bill,
2309 'bill_date_pretty' => time2str('%x', $_->bill),
2310 'renew_date' => $renew_date,
2311 'renew_date_pretty' => time2str('%x', $renew_date),
2312 'expire_date' => $_->expire,
2313 'expire_date_pretty' => time2str('%x', $_->expire),
2318 return { 'dates' => \@array };
2322 sub payment_info_renew_info {
2324 my $renew_info = renew_info($p);
2325 my $payment_info = payment_info($p);
2326 return { %$renew_info,
2334 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2335 return { 'error' => $session } if $context eq 'error';
2337 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2338 or return { 'error' => "unknown custnum $custnum" };
2340 my $date = $p->{'date'};
2344 #freeside-daily -n -d $date fs_daily $custnum
2345 $cust_main->bill_and_collect( 'time' => $date,
2346 'invoice_time' => $now,
2347 'actual_time' => $now,
2348 'check_freq' => '1d',
2351 return { 'error' => '' };
2357 my $session = _cache->get($p->{'session_id'})
2358 or return { 'error' => "Can't resume session" }; #better error message
2360 my $custnum = $session->{'custnum'};
2362 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2363 or return { 'error' => "unknown custnum $custnum" };
2365 my $conf = new FS::Conf;
2367 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2368 or return { 'error' => 'Permission denied' };
2370 my $pkgnum = $p->{'pkgnum'};
2372 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2373 'pkgnum' => $pkgnum, } )
2374 or return { 'error' => "unknown pkgnum $pkgnum" };
2376 my $error = $cust_pkg->suspend(reason => $reasonnum);
2377 return { 'error' => $error };
2383 my $session = _cache->get($p->{'session_id'})
2384 or return { 'error' => "Can't resume session" }; #better error message
2386 my $custnum = $session->{'custnum'};
2388 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2389 or return { 'error' => "unknown custnum $custnum" };
2391 my $pkgnum = $p->{'pkgnum'};
2393 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2394 'pkgnum' => $pkgnum, } )
2395 or return { 'error' => "unknown pkgnum $pkgnum" };
2397 my $error = $cust_pkg->cancel('quiet' => 1);
2398 return { 'error' => $error };
2402 sub provision_phone {
2405 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2407 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2408 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2409 return { 'error' => $session } if $context eq 'error';
2411 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2412 return { 'error' => 'service not found' } unless $svc_phone;
2413 return { 'error' => 'invalid svcnum' }
2414 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2416 $svc_phone->email($p->{'email'})
2417 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2418 $svc_phone->forwarddst($p->{'forwarddst'})
2419 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2420 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2421 return { 'error' => $svc_phone->replace };
2425 unless($p->{'lnp'}) {
2426 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2427 $p->{'lnp_status'} = "portingin";
2428 return _provision( 'FS::svc_phone',
2429 [qw(lnp_desired_due_date lnp_other_provider
2430 lnp_other_provider_account phonenum countrycode lnp_status)],
2431 [qw(phonenum countrycode)],
2438 unless (scalar(@bulkdid)) {
2439 return _provision( 'FS::svc_phone',
2440 [qw(phonenum countrycode)],
2441 [qw(phonenum countrycode)],
2447 # bulk DID order case
2449 foreach my $did ( @bulkdid ) {
2450 $did =~ s/[^0-9]//g;
2451 $error = _provision( 'FS::svc_phone',
2452 [qw(phonenum countrycode)],
2453 [qw(phonenum countrycode)],
2455 'pkgnum' => $p->{'pkgnum'},
2456 'svcpart' => $p->{'svcpart'},
2458 'countrycode' => $p->{'countrycode'},
2459 'session_id' => $p->{'session_id'},
2462 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2464 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2467 sub provision_acct {
2469 warn "provision_acct called\n"
2472 return { 'error' => gettext('passwords_dont_match') }
2473 if $p->{'_password'} ne $p->{'_password2'};
2474 return { 'error' => gettext('empty_password') }
2475 unless length($p->{'_password'});
2477 if ($p->{'domsvc'}) {
2478 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2479 qw ( svcpart pkgnum ) );
2480 return { 'error' => gettext('invalid_domain') }
2481 unless ($domains{$p->{'domsvc'}});
2484 warn "provision_acct calling _provision\n"
2486 _provision( 'FS::svc_acct',
2487 [qw(username _password domsvc)],
2488 [qw(username _password domsvc)],
2494 sub provision_external {
2496 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2497 _provision( 'FS::svc_external',
2506 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2507 warn "_provision called for $class\n"
2510 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2511 return { 'error' => $session } if $context eq 'error';
2513 my $search = { 'custnum' => $custnum };
2514 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2515 my $cust_main = qsearchs('cust_main', $search )
2516 or return { 'error' => "unknown custnum $custnum" };
2518 my $pkgnum = $p->{'pkgnum'};
2520 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2522 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2523 'pkgnum' => $pkgnum,
2525 or return { 'error' => "unknown pkgnum $pkgnum" };
2527 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2529 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2530 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2532 warn "creating $class record\n"
2534 my $svc_x = $class->new( {
2535 'pkgnum' => $p->{'pkgnum'},
2536 'svcpart' => $p->{'svcpart'},
2537 map { $_ => $p->{$_} } @$fields
2539 warn "inserting $class record\n"
2541 my $error = $svc_x->insert;
2544 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2546 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2549 my $return = { 'svc' => $part_svc->svc,
2551 map { $_ => $svc_x->get($_) } @$return_fields
2553 warn "_provision returning ". Dumper($return). "\n"
2562 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2563 return { 'error' => $session } if $context eq 'error';
2565 my $search = { 'custnum' => $custnum };
2566 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2567 my $cust_main = qsearchs('cust_main', $search )
2568 or return { 'error' => "unknown custnum $custnum" };
2570 my $pkgnum = $p->{'pkgnum'};
2572 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2573 'pkgnum' => $pkgnum,
2575 or return { 'error' => "unknown pkgnum $pkgnum" };
2577 my $svcpart = $p->{'svcpart'};
2579 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2580 'svcpart' => $svcpart, } )
2581 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2582 my $part_svc = $pkg_svc->part_svc;
2584 my $conf = new FS::Conf;
2587 'svc' => $part_svc->svc,
2588 'svcdb' => $part_svc->svcdb,
2589 'pkgnum' => $pkgnum,
2590 'svcpart' => $svcpart,
2591 'custnum' => $custnum,
2593 'security_phrase' => 0, #XXX !
2594 'svc_acct_pop' => [], #XXX !
2596 'init_popstate' => '',
2601 small_custview( $cust_main, $conf->config('countrydefault') ),
2605 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2606 && $ret->{'svcdb'} eq 'svc_phone') {
2607 $ret->{'svcnum'} = $p->{'svcnum'};
2608 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2609 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2610 $ret->{'email'} = $svc_phone->email;
2611 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2618 sub unprovision_svc {
2621 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2622 return { 'error' => $session } if $context eq 'error';
2624 my $search = { 'custnum' => $custnum };
2625 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2626 my $cust_main = qsearchs('cust_main', $search )
2627 or return { 'error' => "unknown custnum $custnum" };
2629 my $svcnum = $p->{'svcnum'};
2631 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2632 or return { 'error' => "unknown svcnum $svcnum" };
2634 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2635 unless $cust_svc->cust_pkg->custnum == $custnum;
2637 my $conf = new FS::Conf;
2639 return { 'svc' => $cust_svc->part_svc->svc,
2640 'error' => $cust_svc->cancel,
2642 small_custview( $cust_main, $conf->config('countrydefault') ),
2647 sub myaccount_passwd {
2649 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2650 return { 'error' => $session } if $context eq 'error';
2652 return { 'error' => "New passwords don't match." }
2653 if $p->{'new_password'} ne $p->{'new_password2'};
2655 return { 'error' => 'Enter new password' }
2656 unless length($p->{'new_password'});
2658 #my $search = { 'custnum' => $custnum };
2659 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2660 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2661 my $search = " AND custnum = $1";
2662 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2664 my $svc_acct = qsearchs( {
2665 'table' => 'svc_acct',
2666 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2667 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2668 'LEFT JOIN cust_main USING ( custnum ) ',
2669 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2670 'extra_sql' => $search, #important
2672 or return { 'error' => "Service not found" };
2674 if ( exists($p->{'old_password'}) ) {
2675 return { 'error' => "Incorrect password." }
2676 unless $svc_acct->check_password($p->{'old_password'});
2679 $svc_acct->set_password($p->{'new_password'});
2680 my $error = $svc_acct->replace();
2682 my($label, $value) = $svc_acct->cust_svc->label;
2684 return { 'error' => $error,
2694 my $conf = new FS::Conf;
2695 my $verification = $conf->config('selfservice-password_reset_verification')
2696 or return { 'error' => 'Password resets disabled' };
2698 my $username = $p->{'username'};
2700 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2701 or return { 'error' => 'Account not found' };
2703 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2704 'domsvc' => $svc_domain->svcnum }
2706 or return { 'error' => 'Account not found' };
2708 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2709 or return { 'error' => 'Account not found' };
2711 my $cust_main = $cust_pkg->cust_main;
2715 my( $p, $cust_main ) = @_;
2716 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2717 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2720 my( $p, $cust_main ) = @_;
2721 my $cust_pay = qsearchs({
2722 'table' => 'cust_pay',
2723 'hashref' => { 'custnum' => $cust_main->custnum },
2724 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2728 $p->{'amount'} == $cust_pay->paid;
2731 my( $p, $cust_main ) = @_;
2732 $p->{'zip'} eq $cust_main->zip
2733 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2737 foreach my $verify ( split(',', $verification) ) {
2739 &{ $verify{$verify} }( $p, $cust_main )
2740 or return { 'error' => 'Account not found' };
2744 #okay, we're verified, now create a unique session
2746 my $reset_session = {
2747 'svcnum' => $svc_acct->svcnum,
2750 my $timeout = '1 hour'; #?
2752 my $reset_session_id;
2754 $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2755 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2757 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2761 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2762 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2763 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2764 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2765 my $error = $msg_template->send( 'cust_main' => $cust_main,
2766 'object' => $svc_acct,
2767 'substitutions' => {
2768 'session_id' => $reset_session_id,
2772 return { 'error' => $error }; #????
2775 return { 'error' => '' };
2778 sub check_reset_passwd {
2781 my $conf = new FS::Conf;
2782 my $verification = $conf->config('selfservice-password_reset_verification')
2783 or return { 'error' => 'Password resets disabled' };
2785 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2786 or return { 'error' => "Can't resume session" }; #better error message
2788 my $svcnum = $reset_session->{'svcnum'};
2790 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2791 or return { 'error' => "Service not found" };
2793 return { 'error' => '',
2794 'username' => $svc_acct->username,
2799 sub process_reset_passwd {
2802 my $conf = new FS::Conf;
2803 my $verification = $conf->config('selfservice-password_reset_verification')
2804 or return { 'error' => 'Password resets disabled' };
2806 return { 'error' => "New passwords don't match." }
2807 if $p->{'new_password'} ne $p->{'new_password2'};
2809 return { 'error' => 'Enter new password' }
2810 unless length($p->{'new_password'});
2812 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2813 or return { 'error' => "Can't resume session" }; #better error message
2815 my $svcnum = $reset_session->{'svcnum'};
2817 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2818 or return { 'error' => "Service not found" };
2820 $svc_acct->set_password($p->{'new_password'});
2821 my $error = $svc_acct->replace();
2823 my($label, $value) = $svc_acct->cust_svc->label;
2825 return { 'error' => $error,
2834 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2835 return { 'error' => $session } if $context eq 'error';
2837 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2838 FS::TicketSystem->init();
2840 my $conf = new FS::Conf;
2841 my $queue = $p->{'queue'}
2842 || $conf->config('ticket_system-selfservice_queueid')
2843 || $conf->config('ticket_system-default_queueid');
2845 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2846 my $err_or_ticket = FS::TicketSystem->create_ticket(
2847 '', #create RT session based on FS CurrentUser (fs_selfservice)
2849 'custnum' => $custnum,
2850 'svcnum' => $session->{'svcnum'},
2851 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2854 if ( ref($err_or_ticket) ) {
2855 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2857 return { 'error' => '',
2858 'ticket_id' => $err_or_ticket->id,
2861 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2863 return { 'error' => $err_or_ticket };
2871 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2872 return { 'error' => $session } if $context eq 'error';
2874 return { error => 'requested format not implemented' }
2875 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2877 my $conf = new FS::Conf;
2878 my $age_threshold = 0;
2879 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2880 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2882 my $search = { 'custnum' => $custnum };
2883 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2884 my $cust_main = qsearchs('cust_main', $search )
2885 or return { 'error' => "unknown custnum $custnum" };
2887 # does it make more sense to just run one sql query for this instead of all the
2888 # insanity below? would increase performance greately for large data sets?
2890 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2891 my @part_svc = $cust_pkg->part_svc;
2892 foreach my $part_svc ( @part_svc ) {
2893 if($part_svc->svcdb eq 'svc_phone'){
2894 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2895 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2896 push @svc_phone, $cust_pkg_svc->svc_x
2897 if $cust_pkg_svc->date_inserted >= $age_threshold;
2905 my($xls_r,$xls_c) = (0,0);
2908 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2909 if($p->{'format'} eq 'csv') {
2910 $csv = new Text::CSV_XS { 'always_quote' => 1,
2913 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2914 $content .= $csv->string;
2916 elsif($p->{'format'} eq 'xls') {
2917 my $XLS1 = new IO::Scalar \$content;
2918 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2919 or return { 'error' => "Error opening .xls file: $!" };
2920 $xls = $xls_workbook->add_worksheet('DIDs');
2921 foreach ( @fields ) {
2922 $xls->write(0,$xls_c++,$_);
2927 foreach my $svc_phone ( @svc_phone ) {
2928 my @cols = map { $svc_phone->$_ } @fields;
2929 if($p->{'format'} eq 'csv') {
2930 return { 'error' => 'Unable to create CSV' }
2931 unless $csv->combine(@cols);
2932 $content .= $csv->string;
2934 elsif($p->{'format'} eq 'xls') {
2937 $xls->write($xls_r,$xls_c++,$_);
2943 $xls_workbook->close() if $p->{'format'} eq 'xls';
2945 { content => $content, format => $p->{'format'}, };
2950 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2951 return { 'error' => $session } if $context eq 'error';
2953 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2954 FS::TicketSystem->init();
2955 return { 'error' => 'get_ticket configuration error' }
2956 if $FS::TicketSystem::system ne 'RT_Internal';
2958 # check existence and ownership as part of this
2959 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2960 my $rt_session = FS::TicketSystem->session('');
2961 my $Ticket = FS::TicketSystem->get_ticket_object(
2963 ticket_id => $p->{'ticket_id'},
2966 return { 'error' => 'ticket not found' } if !$Ticket;
2968 if ( length( $p->{'subject'} || '' ) ) {
2970 if ( $p->{'subject'} ne $Ticket->Subject ) {
2971 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2972 return { 'error' => "unable to set subject: $msg" } if !$val;
2976 if(length($p->{'reply'})) {
2977 my @err_or_res = FS::TicketSystem->correspond_ticket(
2979 'ticket_id' => $p->{'ticket_id'},
2980 'content' => $p->{'reply'},
2983 return { 'error' => 'unable to reply to ticket' }
2984 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2987 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2988 my $err_or_ticket = FS::TicketSystem->get_ticket(
2990 'ticket_id' => $p->{'ticket_id'},
2993 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2994 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2996 return { 'error' => $err_or_ticket };
2999 my @custs = @{$err_or_ticket->{'custs'}};
3000 my @txns = @{$err_or_ticket->{'txns'}};
3003 # superseded by check in get_ticket_object
3004 #return { 'error' => 'invalid ticket requested' }
3005 #unless grep($_ eq $custnum, @custs);
3007 foreach my $txn ( @txns ) {
3008 push @filtered_txns, $txn
3009 if ($txn->{'type'} eq 'EmailRecord'
3010 || $txn->{'type'} eq 'Correspond'
3011 || $txn->{'type'} eq 'Create');
3014 warn "$me get_ticket: successful: \n"
3016 return { 'error' => '',
3017 'transactions' => \@filtered_txns,
3018 'ticket_fields' => $err_or_ticket->{'fields'},
3019 'ticket_id' => $p->{'ticket_id'},
3023 sub adjust_ticket_priority {
3025 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3026 return { 'error' => $session } if $context eq 'error';
3028 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3029 FS::TicketSystem->init;
3030 my $ss_priority = FS::TicketSystem->selfservice_priority;
3032 return { 'error' => 'adjust_ticket_priority configuration error' }
3033 if $FS::TicketSystem::system ne 'RT_Internal'
3036 my $values = $p->{'values'}; #hashref, id => priority value
3039 foreach my $id (keys %$values) {
3040 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3041 my $Ticket = FS::TicketSystem->get_ticket_object('',
3043 'custnum' => $custnum,
3046 $ticket_error{$id} = 'ticket not found';
3050 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3051 # We're not going to implement it for RT_External.
3052 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3053 my $new_value = $values->{$id};
3054 next if $old_value eq $new_value;
3056 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3058 # AddCustomFieldValue works fine (replacing any existing value) if it's
3059 # a single-valued custom field, which it should be. If it's not, you're
3060 # doing something wrong.
3062 if ( length($new_value) ) {
3063 ($val, $msg) = $Ticket->AddCustomFieldValue(
3064 Field => $ss_priority,
3065 Value => $new_value,
3069 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3070 Field => $ss_priority,
3071 Value => $old_value,
3075 $ticket_error{$id} = $msg if !$val;
3076 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3078 return { 'error' => '',
3079 'ticket_error' => \%ticket_error,
3080 %{ customer_info($p) } # send updated customer info back
3086 sub _custoragent_session_custnum {
3089 my($context, $session, $custnum);
3090 if ( $p->{'session_id'} ) {
3092 $context = 'customer';
3093 $session = _cache->get($p->{'session_id'})
3094 or return ( 'error' => "Can't resume session" ); #better error message
3095 $custnum = $session->{'custnum'};
3097 } elsif ( $p->{'agent_session_id'} ) {
3100 my $agent_cache = new FS::ClientAPI_SessionCache( {
3101 'namespace' => 'FS::ClientAPI::Agent',
3103 $session = $agent_cache->get($p->{'agent_session_id'})
3104 or return ( 'error' => "Can't resume session" ); #better error message
3105 $custnum = $p->{'custnum'};
3109 return ( 'error' => "Can't resume session" ); #better error message
3112 ($context, $session, $custnum);